I have the following two mySQL tables with the ‘child’ table having a DELETE CASCADE action set from the ‘parent’:
PARENT TABLE
CREATE TABLE `userdetails` (
`userid` int(6) NOT NULL auto_increment,
`forename` varchar(20) NOT NULL,
`surname` varchar(30) NOT NULL,
`emailaddress` varchar(150) NOT NULL,
`password` varchar(200) NOT NULL,
`passwordhint` varchar(20) NOT NULL,
`subscriptionexpiration` date NOT NULL,
`salt` varchar(200) NOT NULL,
PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 AUTO_INCREMENT=2 ;
CHILD TABLE
CREATE TABLE `locations` (
`userid` int(6) NOT NULL,
`locationid` int(6) NOT NULL auto_increment,
`locationname` varchar(80) NOT NULL,
PRIMARY KEY (`locationid`),
KEY `userid` (`userid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `locations`
--
ALTER TABLE `locations`
ADD CONSTRAINT `locations_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `userdetails` (`userid`) ON DELETE CASCADE;
I’m then trying to run the following php script:
<?php
require("phpfile.php");
// Gets data from URL parameters
$userid = $_POST["userid"];
$locationname = $_POST["locationname"];
// Opens a connection to a MySQL server
$connection = mysql_connect ("hostname", $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Insert new row with user data
$query = "INSERT INTO locations (userid, locationname) VALUES ('$userid', '$locationame')";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
and I receive this error:
Invalid query: Cannot add or update a child row: a foreign key constraint fails (`dbname/locations`, CONSTRAINT `locations_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `userdetails` (`userid`) ON DELETE CASCADE)
I’m not sure why I’m getting this as there is a record in the parent table. I’ve been working on this for hours now and I just can’t find the answer.
I just wondered whether someone could perhaps take a look at this please and let me know where I’m going wrong.
Many thanks
Follow the sequence:
First I had insert some data into userdetails
Detail: If I try to insert into child table first it returns to me the message you already got. Then first I need to insert data into userdetails. Pay attention that you have a foreign key, then you need the userid (your key) to insert into child table. Right?
Now take a look how I had insert the data into child table
1 row(s) inserted.
Can you see the userid (2) ?
Then I recommend:
When user register a new account, you also create the insert for location table (child table), ’cause you will need the userid in the location table when user come back to update data. Otherwise you will got this error messages.
I tested here and works! Let me know if works for you.