Cannot add or update a child row .cant insert data - php

cant up date a child raw in my sql
i created the tabels like this :
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the genre table
$genre = #mysql_query( 'CREATE TABLE IF NOT EXISTS genre (
genreName CHAR(15),
rated CHAR(9),
PRIMARY KEY (genreName))
ENGINE innoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
if (!$genre) {
exit('<p>Error creating the genre table<br />'.
'Error: ' . mysql_error() . '</p>');
}
if ($genre) {
echo 'everything went just fine with genre table <br>';
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//create the film table
$film = #mysql_query( 'CREATE TABLE IF NOT EXISTS film (
filmID INT(9) auto_increment ,
filmName CHAR(30),
year INT(4),
genreName CHAR(15),
CONSTRAINT FOREIGN KEY (genreName) REFERENCES genre(genreName)ON DELETE CASCADE ON UPDATE CASCADE,
PRIMARY KEY (filmID))
ENGINE innoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;');
if (!$film) {
exit('<p>Error creating the film table<br />'.
'Error: ' . mysql_error() . '</p>');
}
if ($film) {
echo 'everything went just fine with film table <br>'; }
and the tryed to insert data like this:
$sql = "INSERT INTO film (filmName,year,genreName)
VALUES ('The Avengers', '2012','action')";
and got this eror: Error: INSERT INTO film (filmName,year,genreName) VALUES ('The Avengers', '2012','action')
Cannot add or update a child row: a foreign key constraint fails (osherbi.film, CONSTRAINT film_ibfk_1 FOREIGN KEY (genreName) REFERENCES genre (genreName) ON DELETE CASCADE ON UPDATE CASCADE)

I just made a table with your posts and got the code to work. Try this out.
Table structure for table film :
CREATE TABLE IF NOT EXISTS `film` (
`filmID` int(9) NOT NULL,
`filmName` char(30) NOT NULL,
`year` int(6) NOT NULL,
`genreName` char(15) NOT NULL
)
Table structure for table genre :
CREATE TABLE IF NOT EXISTS `genre` (
`genreName` char(15) NOT NULL,
`rated` char(9) NOT NULL
)
Indexes for table film :
ALTER TABLE `film`
ADD PRIMARY KEY (`filmID`), ADD KEY `genreName` (`genreName`);
Indexes for table genre :
ALTER TABLE `genre`
ADD PRIMARY KEY (`genreName`);
Constraints for table film :
ALTER TABLE `film`
ADD CONSTRAINT `film_ibfk_1` FOREIGN KEY (`genreName`) REFERENCES `genre` (`genreName`) ON DELETE CASCADE ON UPDATE CASCADE;
NOTE :
To insert the data, first you need to insert the data to genre table. If you didn't fill up anything in genre table, you fill face error when you insert data to film table since a column genreName is a Foreign key that referencing to genre table genreName column which was initially null.
Add data to genre table like,
INSERT INTO `test1`.`genre` (`genreName`, `rated`) VALUES ('action', '5');
Then, for film table,
INSERT INTO `test1`.`film` (`filmID`, `filmName`, `year`, `genreName`) VALUES ('1', 'The Avengers', '2012', 'action');
I just tested it out. It's working. Good luck!

Related

FOREIGN KEY ..again

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.

Can't insert : A foreign key constraint fails

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

Problems insert data in database

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.

Joining 2 tables with user input

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')

Trying to update two tables at once MySQL

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.

Categories