How to insert Multiple Query into different tables with foreign key?
I have below code, would anyone help me to modified below code!
$query = "INSERT INTO student(fname, lname, phone, email,status) VALUES('".$_POST["fname"]."','".$_POST["lname"]."','".$_POST["phone"]."','".$_POST["email"]."','".$_POST["status"]."')";
$res = $db_handle->executeQuery($query);
if(!$res){
$message="Please try again!.";
} else {
header("Location:index.php");
}
}
my Tables:
student,
course,
schedule
(id_schedule, id, id_courses, schedule_year, schedule_semester)
"id" connect to student table.
"id_courses" connect to the id_courses into the courses table!
My DB:
--
-- Table structure for table `courses`
--
--
-- Constraints for table `schedule`
--
ALTER TABLE `schedule`
ADD CONSTRAINT `schedule_ibfk_1` FOREIGN KEY (`id_courses`) REFERENCES `courses` (`id_courses`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `schedule_ibfk_2` FOREIGN KEY (`id`) REFERENCES `student` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;
Related
I'm creating an ADD/UPDATE/DELETE system for my database, and while coding the delete query I've found a constraint fails, preventing me from deleting certain data from a specific row.
Delete query:
if (isset($_GET['company'])) {
$id = $_GET['company'];
$query_del = " DELETE company.* , client.* , queries.*
FROM company
INNER JOIN client ON company.idcompany =
client.idcompany
INNER JOIN queries ON
client.idclient =
queries.idclient
WHERE company.idcompany = '" . $id . "'";
$result_del = mysqli_query($con, $query_del);
if ($result_del) {
header("location:companylist.php");
} else {
echo ' Erro: ' . mysqli_error($con);
}
}
Tables required:
company: idcompany , company_name
client: idclient , idcompany
queries: idclient
Error:
Cannot delete or update a parent row: a foreign key constraint fails
(db.client, CONSTRAINT client_ibfk_1 FOREIGN KEY (idcompany)
REFERENCES company (idcompany))
Basically, I'm getting the row number through URL and trying to delete all the data related with that idcompany on all three tables. Does somebody know how I can relate all three tables on a delete query?
To create the required table structure, I used these create statements:
CREATE TABLE company (
idcompany INT,
company_name VARCHAR(31),
PRIMARY KEY (idcompany));
CREATE TABLE clients (
idclient INT,
idcompany INT,
PRIMARY KEY (idclient),
FOREIGN KEY (idcompany) REFERENCES company(idcompany) ON DELETE CASCADE);
CREATE TABLE queries (
idclient INT,
FOREIGN KEY (idclient) REFERENCES clients(idclient) ON DELETE CASCADE);
Then, to delete all references to a company, you can simply run
DELETE FROM company WHERE idcompany = (insert company id variable here);
You can view a working sql demo here.
If you need to change the constrain to contain DELETE CASCADE then look at this post.
I have a big problem with this SQL error when I'm trying to insert a event in my database with this PDO.
SQL:
$subsquery1 = "SELECT cat_id FROM categories WHERE cat_name = ".$event_cat;
$subsquery2 = "SELECT tournament_id FROM tournaments WHERE tournament_name = ".$event_tournament;
$sqlx = "INSERT INTO events(event_team1, event_team2, event_cat, event_tournament, event_start_at, event_end_to, event_by) VALUES(:event_team1, :event_team2, :event_cat, :event_tournament, :event_start_at, :event_end_to, :event_by)";
// Prepare statement
$statementx = $pdo->prepare($sqlx);
// execute the query
$resultx = $statementx->execute(array(':event_team1' => $event_team1, ':event_team2' => $event_team2, ':event_cat'=> $subsquery1, ':event_tournament'=> $subsquery2, ':event_start_at' => $event_start_at, ':event_end_to' => $event_end_to,':event_by'=>$event_by));
SQL error:
Integrity constraint violation: 1452 Cannot add or update a child
row: a foreign key constraint fails (datenbank.events, CONSTRAINT
events_ibfk_1 FOREIGN KEY (event_cat) REFERENCES categories
(cat_id) ON DELETE CASCADE ON UPDATE CASCADE)
-- Table structure for table `events`
CREATE TABLE `events` (
`event_id` int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
`event_team1` varchar(255) NOT NULL,
`event_team2` varchar(255) NOT NULL,
`event_start_at` timestamp NOT NULL,
`event_end_to` timestamp NOT NULL,
`event_cat` int(8) NOT NULL,
`event_by` int(8) NOT NULL,
`event_tournament` int(8) NOT NULL,
KEY `event_cat` (`event_cat`),
KEY `event_by` (`event_by`),
KEY `event_tournament` (`event_tournament`)
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- Constraints for table posts
ALTER TABLE `posts` ADD CONSTRAINT `posts_ibfk_1` FOREIGN KEY (`post_event`) REFERENCES `events` (`event_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `posts_ibfk_2` FOREIGN KEY (`post_by`) REFERENCES `users` (`id`) ON UPDATE CASCADE;
-- Constraints for table events
ALTER TABLE `events` ADD CONSTRAINT `events_ibfk_1` FOREIGN KEY (`event_cat`) REFERENCES `categories` (`cat_id`) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `events_ibfk_2` FOREIGN KEY (`event_by`) REFERENCES `users` (`id`) ON UPDATE CASCADE,
ADD CONSTRAINT `events_ibfk_3` FOREIGN KEY (`event_tournament`) REFERENCES `tournaments` (`tournament_id`) ON DELETE CASCADE ON UPDATE CASCADE;
What can I try to solve this?
Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (datenbank.events,
CONSTRAINTevents_ibfk_1FOREIGN KEY (event_cat)
REFERENCEScategories(cat_id)
You are performing an insert to table events with a value being placed in column event_cat.
That value does not already exist in table categories in the column cat_id.
And you said it must. So the db engine says it won't do it. It is faithfully obeying your orders.
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
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!
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.