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
Related
My query, in PHP, is:
$upd2 = $di->getDb()->prepare('INSERT INTO '. self::TABLE . '_agrupamento_avaliacao (idSemana, idEntidade_agrupamento) VALUES(?, ?) ON DUPLICATE KEY UPDATE idEntidade_agrupamento=VALUES(idEntidade_agrupamento)');
$upd2->Execute(array($semana, $agrupamento));
But it isn't working. It's inserting the same data.
I tested querying:
INSERT INTO entidade_agrupamento_avaliacao (idSemana, idEntidade_agrupamento) VALUES(17, 2808) ON DUPLICATE KEY UPDATE idEntidade_agrupamento=VALUES(idEntidade_agrupamento)
But it also insert the same data instead of update the data.
My table is:
CREATE TABLE `entidade_agrupamento_avaliacao` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`idSemana` INT(10) UNSIGNED NOT NULL,
`idEntidade_Agrupamento` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `FK__semana` (`idSemana`),
INDEX `FK_entidade_agrupamento_avaliacao_entidade_agrupamento` (`idEntidade_Agrupamento`),
CONSTRAINT `FK__semana` FOREIGN KEY (`idSemana`) REFERENCES `semana` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_entidade_agrupamento_avaliacao_entidade_agrupamento` FOREIGN KEY (`idEntidade_Agrupamento`) REFERENCES `entidade_agrupamento` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=4
;
What is the problem?
Consider "$di->getDb()->prepare" as the PDO Statement prepare.
This is your query:
INSERT INTO '. self::TABLE . '_agrupamento_avaliacao (idSemana, idEntidade_agrupamento)
VALUES(?, ?)
ON DUPLICATE KEY UPDATE idEntidade_agrupamento = VALUES(idEntidade_agrupamento)');
The only unique index that you have on the table is the primary key on id. This is auto-incremented, so it is not going to generate a duplicate.
Presumably, you want to declare idSemana as being unique. Then the duplicate key can be caught. You were probably thinking that index idSemana is sufficient for this purpose, but you really need unique idSemana.
First of all, it's not a duplicate! I already saw some related questions about it and I tried to do what they said in those answers and didn't work..
Here is an image of my database structure
As you can see, everything is all right, the relations were established correctly BUT when I try to add an event appears this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tvfootball.all_streams, CONSTRAINT fk_channels FOREIGN KEY (channel_id) REFERENCES channels (ID) ON DELETE CASCADE ON UPDATE NO ACTION)' in C:\xampp\htdocs\aaa\admin\addStream.php:16 Stack trace: #0 C:\xampp\htdocs\aaa\admin\addStream.php(16): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\aaa\admin\addStream.php on line 16
and if I try to insert an channel, I get this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tvfootball.all_streams, CONSTRAINT fk_events FOREIGN KEY (event_id) REFERENCES events (ID) ON DELETE CASCADE ON UPDATE NO ACTION)' in C:\xampp\htdocs\aaa\admin\addStream.php:31 Stack trace: #0 C:\xampp\htdocs\aaa\admin\addStream.php(31): PDOStatement->execute() #1 {main} thrown in C:\xampp\htdocs\aaa\admin\addStream.php on line 31
The thing is... It inserts data to streams table, BUT doesn't insert anything in all_streams
Here is my SQL
DROP TABLE IF EXISTS `all_streams`;
CREATE TABLE `all_streams` (
`event_id` int(11) DEFAULT '0',
`stream_id` int(11) DEFAULT '0',
`channel_id` int(11) DEFAULT '0',
`date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY `fk_streams` (`stream_id`),
KEY `fk_events` (`event_id`),
KEY `fk_channels` (`channel_id`),
CONSTRAINT `fk_channels` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_events` FOREIGN KEY (`event_id`) REFERENCES `events` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_streams` FOREIGN KEY (`stream_id`) REFERENCES `streams` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here is my PHP
if(isset($_POST['addStreamsEvents'])){
extract($_POST);
$statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
$statement->bindParam(1,$stream);
$statement->execute();
$id=$db->lastInsertId();
$statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id)VALUES (?,?)");
$statement_join->bindParam(1,$event);
$statement_join->bindParam(2,$id);
$statement_join->execute();
}
if(isset($_POST['addStreamsChannels'])){
extract($_POST);
$statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
$statement->bindParam(1,$stream);
$statement->execute();
$id=$db->lastInsertId();
$statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
$statement_join->bindParam(1,$event);
$statement_join->bindParam(2,$id);
$statement_join->execute();
}
Does someone have any idea what I'm doing wrong?
BTW:
I already tried it: SET FOREIGN_KEY_CHECKS=0; and didn't work..
The first thing I notice is that you have a default value of zero set on a foreign key constrained column, but as you said in the comments, the value of zero doesn't exist as a primary key, so your insert fails because you don't specify it in the query.
`event_id` int(11) DEFAULT '0',
`stream_id` int(11) DEFAULT '0',
`channel_id` int(11) DEFAULT '0',
If you're going to keep using this default, then you must explicitly insert NULL or a valid id.
Here's a working example that changes this:
INSERT INTO all_streams (event_id,stream_id) VALUES (?,?)
into this:
INSERT INTO all_streams (event_id,stream_id,channel_id) VALUES (?,?, NULL)
However, I think the best thing would be to remove those default values, because it doesn't make sense to me, which works also.
It's unclear without seeing your form, but another problem you might not have noticed is that you're using the same input value named event for event_id and channel_id
$statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id)VALUES (?,?)");
$statement_join->bindParam(1,$event);
...
$statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
$statement_join->bindParam(1,$event);
Here's the working example reproduced as best I could filling in the missing values for your tables and form.
<form method="POST">
<input type="hidden" name="addStreamsEvents"/>
<input type="hidden" name="addStreamsChannels"/>
<label for="stream">Stream</label>
<input type="text" name="stream"/>
<label for="event">Event or Channel ID</label>
<input type="number" name="event" value="1"/>
<input type="submit" value="Submit"/>
</form>
<?php
// returns an instance of PDO
// https://github.com/jpuck/qdbp
$db = require __DIR__.'/streams_Dtm905_A.pdo.php';
if(isset($_POST['addStreamsEvents'])){
extract($_POST);
$statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
$statement->bindParam(1,$stream);
$statement->execute();
$id=$db->lastInsertId();
$statement_join = $db->prepare("INSERT INTO all_streams (event_id,stream_id) VALUES (?,?)");
$statement_join->bindParam(1,$event);
$statement_join->bindParam(2,$id);
$statement_join->execute();
}
if(isset($_POST['addStreamsChannels'])){
extract($_POST);
$statement = $db->prepare("INSERT INTO streams (link) VALUES (?)");
$statement->bindParam(1,$stream);
$statement->execute();
$id=$db->lastInsertId();
$statement_join = $db->prepare("INSERT INTO all_streams (channel_id, stream_id) VALUES (?,?)");
$statement_join->bindParam(1,$event);
$statement_join->bindParam(2,$id);
$statement_join->execute();
}
DROP TABLE IF EXISTS `all_streams`;
DROP TABLE IF EXISTS `streams`;
DROP TABLE IF EXISTS `events`;
DROP TABLE IF EXISTS `channels`;
CREATE TABLE `channels` (
`id` int(11) AUTO_INCREMENT PRIMARY KEY,
`name` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `events` (
`id` int(11) AUTO_INCREMENT PRIMARY KEY,
`something` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `streams` (
`id` int(11) AUTO_INCREMENT PRIMARY KEY,
`link` varchar(11)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `all_streams` (
`event_id` int(11),
`stream_id` int(11),
`channel_id` int(11),
`date_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
KEY `fk_streams` (`stream_id`),
KEY `fk_events` (`event_id`),
KEY `fk_channels` (`channel_id`),
CONSTRAINT `fk_channels` FOREIGN KEY (`channel_id`) REFERENCES `channels` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_events` FOREIGN KEY (`event_id`) REFERENCES `events` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION,
CONSTRAINT `fk_streams` FOREIGN KEY (`stream_id`) REFERENCES `streams` (`ID`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- seed data
INSERT INTO `channels` (`name`) VALUES ('channel 1');
INSERT INTO `events` (`something`) VALUES ('event 1');
In a few words, you have references on non-existing records (null values).
For instance, you want to add your foreign keys to the and you have already had a record in table all streams with event_id=14, stream_id=2, channel_id=91 (or vice versa have already had constraints but want to add a record) but in the table events there is no record with id=14 or/and there is no record in the stream table with id=2 or/and there is no record in the channel table with id=91.
Also, you are not allowed to set default values for foreign keys!
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.
I'm developing a web-based application with PHP/MySQL + Yii Framework. The problem occurs as a constraint check error in a transaction.
I have the following tables:
User
CREATE TABLE IF NOT EXISTS `User` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(64) DEFAULT NULL,
`surname` varchar(64) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`creation_date` datetime DEFAULT NULL,
`last_login_date` datetime DEFAULT NULL,
`status` tinyint(1) DEFAULT '0',
`level` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=40 ;
CandidateInfo
CREATE TABLE IF NOT EXISTS `CandidateInfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) DEFAULT NULL,
`candidate_status_id` int(11) DEFAULT NULL,
`name` varchar(64) DEFAULT NULL,
`surname` varchar(64) DEFAULT NULL,
`email` varchar(128) DEFAULT NULL,
`gender` tinyint(1) DEFAULT '0',
`date_of_birth` datetime DEFAULT NULL,
`home_phone` varchar(20) DEFAULT NULL,
`mobile_phone` varchar(20) DEFAULT NULL,
`creation_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`rating` tinyint(1) DEFAULT '0',
`location` varchar(100)DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_candidateinfo_user` (`id`),
KEY `FK_candidateinfo_candidatestatus` (`candidate_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=26 ;
Basically I'm trying to add a new row to User table, and then use the insert id to add a new row to the CandidateInfo table (user_id column)
The php code is as
$transaction = Yii::app()->db->beginTransaction();
try {
$user->save();
$candidate->setAttribute('user_id', $user->id);
$candidate->save();
$transaction->commit();
} catch (Exception $e) {
$transaction->rollBack();
var_dump($e->getMessage());
}
The error is:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`origo`.`CandidateInfo`, CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION). The SQL statement executed was: INSERT INTO `CandidateInfo` (`gender`, `rating`, `name`, `surname`, `email`, `date_of_birth`, `home_phone`, `mobile_phone`, `user_id`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8)
When i check the mysql query logs, i see that it takes the right user_id for the INSERT statement for CandidateInfo table. But fails with the above error. From my understanding, it is supposed to work, but may be i am mistaken and this is not the way transactions are meant to work.
Both tables are InnoDB.
Thanks in advance.
Edit:
Sorry forgot to paste the FK relations.
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
should be
ALTER TABLE `CandidateInfo`
ADD CONSTRAINT `FK_candidateinfo_candidatestatus` FOREIGN KEY (`candidate_status_id`) REFERENCES `CandidateStatus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `FK_candidateinfo_user` FOREIGN KEY (`user_id`) REFERENCES `User` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
you've got id references id in yours.
Your error stack:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (origo.CandidateInfo, CONSTRAINT FK_candidateinfo_user FOREIGN KEY (id) REFERENCES User (id) ON DELETE NO ACTION ON UPDATE NO ACTION).
The SQL statement executed was:
INSERT INTO `CandidateInfo`
( `gender`, `rating`, `name`, `surname`, `email`,
`date_of_birth`, `home_phone`, `mobile_phone`, `user_id`
)
VALUES ( :yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6, :yp7, :yp8 )
Your CandidateInfo table defines id field as auto_increment primary key field and a foreign key as well.
And your insert statement does not include id, read from its parent user table.
And hence on insert a new id value is generated for candidateinfo table and applied.
Which intern failed as it did not match any of the primary key id value of the parent user table.
And hence is the error.
Note:
In a child table if your are referring a pk field of a master as a foreign key field,
you should not apply auto_increment for it but just refer.
And looking closely the candidateinfo structure, I feel that you might want to map use_id to user.id field. Making that change, with proper foreign key definition used, would resolve your problem.