Alright I have the foreign keys set up and I'm able to join the tables via the sql tab in phpmyadmin, but I can't figure out how to get things to work properly when I allow a user to input the values via a form. Right now I'm just playing around with a very basic form that allows first name, last name, and phone number. First and Last name get sent to a table named Customer and phone number gets passed to a table called Customer_Number. The problem is that now when I enter values into the input fields, First and Last name saved to the DB table, but phone number doesn't save and spits out this error message Cannot add or update a child row: a foreign key constraint fails (``.Customer_Number, CONSTRAINT Customer_Number_ibfk_1 FOREIGN KEY (Customer_ID) REFERENCES Customer (Customer_ID))
Is there a way I can just add these values and the foreign key for my Customer_Number table update according to the correct customer?
Here is my code:
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$First=mysqli_real_escape_string($con,$_POST["FirstName"]);
$Last=mysqli_real_escape_string($con, $_POST["LastName"]);
if(!empty($_POST["FirstName"]) && !empty($_POST["LastName"])){
$sql="INSERT INTO Customer(First,Last)
VALUE('$First', '$Last')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
<?php
$con=mysqli_connect("");
if(mysqli_connect_errno()){
echo "There was a mistake connecting". mysqli_connect_errno();
}
$Phone=mysqli_real_escape_string($con,$_POST["Number"]);
if(!empty($_POST["Number"])){
$sql="INSERT INTO Customer_Number(Number)
VALUE('$Phone')";
if(!mysqli_query($con,$sql)) {
die("ERROR". mysqli_error($con));
}else{
echo"record added";
}
}
mysql_close($con);
?>
And here is my table information:
CREATE TABLE `Customer` (
`Customer_ID` int(11) NOT NULL AUTO_INCREMENT,
`First` varchar(255) NOT NULL,
`Last` varchar(255) NOT NULL,
PRIMARY KEY (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
CREATE TABLE `Customer_Number` (
`Num_ID` int(11) NOT NULL AUTO_INCREMENT,
`Customer_ID` int(11) NOT NULL,
`Number` varchar(255) NOT NULL,
PRIMARY KEY (`Num_ID`),
KEY `Customer_ID` (`Customer_ID`),
CONSTRAINT `Customer_Number_ibfk_1` FOREIGN KEY (`Customer_ID`) REFERENCES `Customer` (`Customer_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
I know there has got to be a way to do this, but I'm new to this and my google searches has only really covered how to do this via phpMyAdmin and manually entering in the foreign key values.
Since Customer_Number.Customer_ID is a foreign key pointing to the corresponding Customer row, you need to set Customer_Number.Customer_ID to the correct value when inserting the number after inserting the Customer.
As long as you're using the same connection (ie skip closing/reopening it between the queries), you can use LAST_INSERT_ID() to get the Customer_ID of the just inserted customer, something like (the SQL part only);
INSERT INTO Customer(First,Last)
VALUES ('$First', '$Last')
INSERT INTO Customer_Number(Customer_ID, Number)
VALUES (LAST_INSERT_ID(), '$Phone')
Related
I have read and searched all the site, but nothing I had found worked for me...so please help a newbie understand what he is doing wrong.
So I am trying to create an add to favorite function.
I need to create 3 tables. The first two worked like magic, but the 3rd one ...well I got in the trouble with the FOREIGN KEY
I get no error message, but it won't create the 3rd table.
Here are my codes:
<?php
$connect = mysql_connect("127.0.0.1","root","");
$db = mysql_select_db("mydb");
mysql_query("CREATE TABLE IF NOT EXISTS users
(
userid bigint,
firstname varchar(25),
lastname varchar(15),
email varchar(250),
gender varchar(10),
username varchar(15),
password varchar(15),
age int,
activ boolean,
date TIMESTAMP NULL default CURRENT_TIMESTAMP
)ENGINE=INNODB
");
mysql_query("CREATE TABLE IF NOT EXISTS products (
productid int(11) NOT NULL AUTO_INCREMENT,
productname varchar(100) NOT NULL,
productdescription varchar(250) NOT NULL,
price decimal(6,2) NOT NULL,
PRIMARY KEY (`productid`)
) ENGINE=INNODB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ");
mysql_query("CREATE TABLE IF NOT EXISTS favorites
(
userid bigint NOT NULL,
productid int(11) NOT NULL,
PRIMARY KEY (userid, productid),
FOREIGN KEY (userid) REFERENCES user (userid) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (productid) REFERENCES product (productid) ON DELETE CASCADE ON UPDATE CASCADE
)ENGINE=INNODB
");
echo "The DataBase was successfully created!";
mysql_close();
?>
The foreign keys refer to non-existing tables.
The tables are names users and products while the third table refers to them as user and product (singular).
"userid" of "user" table must be primary key.
I have the following tables:
CREATE TABLE IF NOT EXISTS `location`(
`ID` int(11) NOT NULL,
`name` varchar(25) NOT NULL,
`water` varchar(25) NOT NULL,
`fodder` varchar(25) NOT NULL,
`access` varchar(25) NOT NULL,
PRIMARY KEY (`ID`)
KEY `water` (`water`)
KEY `fodder` (`fodder`)
KEY `access` (`access`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `watercondition`(
`ID` int(11) NOT NULL,
`watervalue` varchar(25) NOT NULL,
PRIMARY KEY (`watervalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `foddercondition`(
`ID` int(11) NOT NULL,
`foddervalue` varchar(25) NOT NULL,
PRIMARY KEY (`foddervalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
CREATE TABLE IF NOT EXISTS `accesscondition`(
`ID` int(11) NOT NULL,
`accessvalue` varchar(25) NOT NULL,
PRIMARY KEY (`accessvalue`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ;
And for constraints table :
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk2` FOREIGN KEY (`water`) REFERENCES `watercondition` (`watervalue`),
ADD CONSTRAINT `location_ibfk3` FOREIGN KEY (`fodder`) REFERENCES `foddercondition` (`foddervalue`),
ADD CONSTRAINT `location_ibfk4` FOREIGN KEY (`access`) REFERENCES `accesscondition` (`accessvalue`);
In my php file, i want to insert a value to all of the table like this :
$sqlwater = "INSERT INTO `watercondition` (`ID`, `watervalue`) VALUES ('".$_SESSION['loc_id']."', '$watervalue')";
$resultwater = mysqli_query($con, $sqlwater) or die (mysqli_error($con));
$sqlfodder = "INSERT INTO `foddercondition` (`ID`, `foddervalue`) VALUES ('".$_SESSION['loc_id']."', '$foddervalue')";
$resultfodder = mysqli_query($con, $sqlfodder) or die (mysqli_error($con));
$sqlaccess = "INSERT INTO `accesscondition` (`ID`, `accessvalue`) VALUES ('".$_SESSION['loc_id']."', '$accessvalue')";
$resultaccess = mysqli_query($con, $access) or die (mysqli_error($con));
$sqlloc = "INSERT INTO `location` (`ID`, `name`) VALUES ('".$_SESSION['loc_id']."', '$name')";
$resultaccess = mysqli_query($con, $access) or die (mysqli_error($con));
But when I execute the php file, I get this error :
Cannot add or update a child row: a foreign key constraint fails (mydb.location, CONSTRAINT location_ibfk2 FOREIGN KEY (water) REFERENCES watercondition (watervalue))
When I check on my db, the value from water, fodder, and access have already been inserted db, but not in my location table.
The insert into the location table must also include values for the water, fodder and location columns. They are columns in the location table and cannot just be ignored.
Also you were using the wrong query variable in the final query.
I guess what is happening here is that the constraints are being validated by MYSQL before it checks that you have values for all the NOT NULL fields, so you get the constraint error before the more obvious one about missing column values.
$sqlloc = "INSERT INTO `location`
(`ID`, `name`, `water`, `fodder`, `location`)
VALUES ('{$_SESSION['loc_id']}', '$name',
'$watervalue', '$foddervalue', '$accessvalue' )";
$resultaccess = mysqli_query($con, $sqlloc) or die (mysqli_error($con));
You should insert foreign key to your location table to maintain relation you have created before.
Your query for location should be like
`$sqlloc = "INSERT INTO 'location' ('ID', 'name', 'water', 'footer', 'access') VALUES ('".$_SESSION['loc_id']."', '$name', 'water-related-id', 'fodder-related-id, 'access-related-id)";`
Anyway, primary key for a table should be 'id' column and foreign key should be other table's primary key, so your constraints should be
ALTER TABLE 'location'
ADD CONSTRAINT 'location_ibfk2' FOREIGN KEY ('water') REFERENCES 'watercondition' ('id'),
ADD CONSTRAINT 'location_ibfk3' FOREIGN KEY ('fodder') REFERENCES 'foddercondition' ('id'),
ADD CONSTRAINT 'location_ibfk4' FOREIGN KEY ('access') REFERENCES 'accesscondition' ('id');
And, your foreign key data type should match referenced table's key which in your case is int(11).
Are you doing this for college assignment?
Change your last insert statement like below:
"INSERT INTO `location` (`ID`, `name`,`water`,`fodder`,`access`) VALUES
('".$_SESSION['loc_id']."', '$name','$watervalue','$foddervalue','$accessvalue')";
Explanation:
ERD:
Look the yellow marked tables are the parent tables and your location table is child table.
So according to MySQL you cannot add or update a child table row (location) by some foreign key values which don't exist in corresponding parent table(s).
In your first three insert statements you are updating your three parent tables which is fine.
But in your final insert statement you are trying to update your child table where you provide with no values for those foreign keys which is an exception.
SQL FIDDLE
Reference
Twothings to note here:
First of all, your insert is not working because you made all the foreign keys "NOT NULL" fields, so when you insert a record on the location table you must provide those values.
Second, you must make sure the fields that are foreign keys has the same data type on the original table. In your code you are using INT(11) id fields on the original tables but are using VARCHAR(25) on the location table and you are linking to the field holding the value instead of linking to the primary key (id) field of the referenced table.
Kind regards,
Daniel
I made a database recipes, it consists of; recipe's name, ID number, ingredients, preperation, image etc.
After that I made a php and html script so I can search in the databese (for example: dinner with preperation time less than 45 min.).
No I'm working on a php script to insert new recipes. I can insert $sql1. But when I try to insert $sql2 it says:
Could not enter data retval 2: Cannot add or update a child row: a foreign key constraint fails (recepten.benodigdheid, CONSTRAINT benodigdheid_ibfk_1 FOREIGN KEY (ID) REFERENCES gerecht (ID))
I understand the problem is in the child/parent relation and the foreign key, but I can't find the problem. Do you first have to add data in 'Ingredient'? Or first in 'Gerecht'?
Below I wrote down part of the script, I can give more if required.
PHP script to insert new recipe:
$sql1="INSERT INTO Gerecht ( gerechtnaam, personen, categorie, bereidingstijd, bereidingswijze, plaatje)
VALUES ('$gerechtnaam','$personen','$categorie','$bereidingstijd','$bereidingswijze','$plaatje')";
$sql2="INSERT INTO Benodigdheid (benodigdheden)
VALUES ('$benodigdheden')";
$sql3="INSERT INTO Product (ingredientnaam, eenheidnaam)
VALUES ('$ingredientnaam1', '$eenheid1')";
$sql4="INSERT INTO Ingredient (ingredientnaam, hoeveelheid)
VALUES ('$ingredientnaam1', '$hoeveelheid1')";
$retval1 = mysqli_query($db, $sql4 );
if(! $retval1 )
{
die('Could not enter data retval 1: ' . mysqli_error($db));
}
echo "Entered data retval1 successfully\n";
$retval2 = mysqli_query($db, $sql2 );
if(! $retval3 )
{
die('Could not enter data retval 2: ' . mysqli_error($db));
}
echo "Entered data retval2 successfully\n";
Create script database:
CREATE TABLE Gerecht
(ID INT(3) AUTO_INCREMENT NOT NULL,
gerechtnaam VARCHAR(35) NOT NULL,
personen NUMERIC(2) NOT NULL,
categorie VARCHAR(25) NOT NULL,
bereidingstijd NUMERIC(3) NOT NULL,
bereidingswijze TEXT NOT NULL,
plaatje VARCHAR(250) NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE Benodigdheid
(ID INT(3) NOT NULL,
benodigdheden VARCHAR(35) NOT NULL,
PRIMARY KEY (ID, benodigdheden),
FOREIGN KEY (ID) REFERENCES Gerecht (ID)
);
CREATE TABLE Eenheid
(eenheidnaam VARCHAR(12) NOT NULL,
PRIMARY KEY (eenheidnaam)
);
CREATE TABLE Product
(ingredientnaam VARCHAR(35) NOT NULL,
eenheidnaam VARCHAR(12),
PRIMARY KEY (ingredientnaam),
FOREIGN KEY (eenheidnaam) REFERENCES Eenheid (eenheidnaam)
);
CREATE TABLE Ingredient
(ID INT(3) NOT NULL,
ingredientnaam VARCHAR(35) NOT NULL,
hoeveelheid NUMERIC(4) NOT NULL,
PRIMARY KEY (ID, ingredientnaam),
FOREIGN KEY (ID) REFERENCES Gerecht (ID),
FOREIGN KEY (ingredientnaam) REFERENCES Product (ingredientnaam)
);
You are not trying to insert the ID of the Gerecht when inserting into Benodigheid. You MUST insert this value as well since there is a referential integrity constraint on the table. After your first SQL insert, you need to read out the id of the last inserted Gerecht record (perhaps by using mysqli_insert_id() and then add that id value in the insert to Benodigheid table. So $sql2 should look like this:
$sql2="INSERT INTO Benodigdheid (ID, benodigdheden)
VALUES ($id_from_sql1, '$benodigdheden')";
Your Benodigdheid table also seems flawed in that it should have its own autoincrement primary key as well as the foreign key referencing Gerecht. Though in looking at what you are doing, it seems like there is 1 to 1 relationship between Gerecht and Benodigheid, so I actually don't know why you wouldn't just have benogdigheid as a column on Gerecht if this is your intent.
I generally looking over your schema, it would seem clear that you need to get in the practice of adding autoincrement primary keys to your tables (which is commonly done for most all relational DB tables). You are going to have the same problem on your ingredient tables
You have set a constraint on the table Benodigdheid from its key ID to the primary key ID in Gerecht. You need a separate foreign key. You can't have the primary key and the foreign key be the same column.
I don't understand the words so I don't know exactly what fits to what, but that constraint is a problem and gives you the error.
I've been trying make my database work so that cuisineid columns in different tables are linked together. I've got as far as defining the Primary and Foreign Keys on the two tables but when I try and update them now I get this error:
Insert failed: Cannot add or update a child row: a foreign key constraint fails
(`ml11maj_Databasetest`.`Nation`, CONSTRAINT `Foreign Key` FOREIGN KEY (`cuisineid`)
REFERENCES `recipename` (`cuisineid`) ON DELETE CASCADE ON UPDATE CASCADE)
The rest of the upload works, but nothing is added into the Nation(cuisine id is the primary key and currently set to AI) table, the code to insert currently looks like this
if ($cuisine !=''){
$query = "INSERT INTO`Nation`(cuisine_type)VALUES('$cuisine')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
}
EDIT
Nation Table Contains two columns
-Cuisine_type Varchar
-cuisineid int Primary
The recipename table
-recipeid int(255) AUTO_INCREMENT
-mealname text
-b_l_d varchar(30)
-ingredients text
-hours int(11)
-minutes int(11)
-recipe text utf8_bin
-feeds int(11)
-imagepath varchar(100)
-userid int(11)
-cuisineid int(255)
Your insert does not have a cuisine_id, so the foreign key constraint fails, as it tells you. If you want that column to be NULLABLE then you can omit the cuisine_id column in your insert.
These are my tables:
create table sender(
sno varchar(6) not null,
sfname varchar(15) not null,
slname varchar(10) not null,
sphone varchar(10),
saddress varchar(40) not null,
constraint pk_sender primary key(sno)
);
create table courier(
cno varchar(6),
cost double precision not null,
weight double precision not null,
del_stat varchar(20) not null,
no_cour int(10),
sno varchar(6),
constraint fk_courier foreign key(sno)
references sender(sno),constraint pk_courier primary key(cno)
);
And this is my php code:
<?php
session_start();
$_SESSION['x']=$_POST[sno];
$con=mysqli_connect("localhost","root","project123","project");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values (concat('SN','$_POST[sno]'),'$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour) values (concat('CN','$_POST[cno]'),'$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]')";
if(!mysqli_query($con,$sql1) && !mysqli_query($con,$sql2))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
But I'm getting error
Error: Cannot add or update a child row: a foreign key constraint fails (project.courier, CONSTRAINT fk_courier FOREIGN KEY (sno) REFERENCES sender (sno))
So please tell me how to insert values to foreign key.
It seems that you're not setting the foreign key value on your child table insert. Your courier table have a column sno VARCHAR(6) that references sender.sno VARCHAR(6) right? So you have to provide it value. In order to relate two fields as foreign key, you have to set a valid value for the child column existing on the parent related column.
Anyway, you should run those two queries like this:
$sno = "SN$_POST[sno]";
$cno = "CN$_POST[cno]";
$sql1="insert into sender(sno,sfname,slname,sphone,saddress) values ('$sno','$_POST[sf]','$_POST[sl]','$_POST[sph]','$_POST[sad]')";
if(mysqli_query($con,$sql1))
{
$sql2="insert into courier(cno,cost,weight,del_stat,no_cour, sno) values ('$cno','$_POST[cst]','$_POST[wght]','$_POST[del]','$_POST[num]', '$sno')";
if (mysqli_query($con,$sql2))
{
// Success
}
else
{
die('Error on query 2: ' . mysqli_error($con));
}
}
else
{
die('Error on query 1: ' . mysqli_error($con));
}
You can see here how to get the last inserted id from an auto_increment field. If you're not using an auto_increment field, you have to select it in other way that fits your needs.
I hope this helps.
UPDATE: I have change those variables sno and cno because you can avoid concatenating it inside your query. You can do that that way. I realize that you already have the sno value, so you don't need to query again after it. That code may now work.