I’m having a problem with foreign key in mysql.I’m trying to insert a row in table that contains foreign key but I’m facing with this error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`prj1`.`tempoccasion`, CONSTRAINT `tempoccasion_ibfk_1` FOREIGN KEY (`tempid`) REFERENCES `temp` (`tempid`) ON DELETE CASCADE ON UPDATE CASCADE)
I’ve done SHOW CREATE TABLE query on tables(temp and occasion are source table-tempoccasion is the table with the foreign key)
CREATE TABLE `temp` (
`tempid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(30) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
`image` text NOT NULL,
`code` text NOT NULL,
PRIMARY KEY (`tempid`),
UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT
n CREATE TABLE `occasion` (
`occasionid` int(11) NOT NULL AUTO_INCREMENT,
`occasionname` varchar(30) CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
`year` varchar(11) NOT NULL,
`month` varchar(11) NOT NULL,
`day` varchar(11) NOT NULL,
`comment` text CHARACTER SET utf8 COLLATE utf8_persian_ci NOT NULL,
PRIMARY KEY (`occasionid`),
UNIQUE KEY `occasionname` (`occasionname`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT
CREATE TABLE `tempoccasion` (
`tempid` int(11) NOT NULL,
`occasionid` int(11) NOT NULL,
PRIMARY KEY (`tempid`,`occasionid`),
KEY `occasionid` (`occasionid`),
CONSTRAINT `tempoccasion_ibfk_2` FOREIGN KEY (`occasionid`) REFERENCES `occasion` (`occasionid`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `tempoccasion_ibfk_1` FOREIGN KEY (`tempid`) REFERENCES `temp` (`tempid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ROW_FORMAT=COMPACT
the query that makes error is(that is written in php):
$tn=$_GET["tname"];
$on=$_GET["oid"];
$i=$_GET["image"];
$c=$_GET["code"];
$q="insert into temp(name,image,code)values('$tn','$i','$c')";
$r=mysql_query($q)or die("invalid query");
if ($r)
{
$q1="select tempid from temp where name like '$tn'";
$row1=mysql_query($q1)or die("invalid query1");
if ($row1)
{
$tid=$row1['tempid'];
echo $tid;
$q2="insert into tempoccasion (tempid,occasionid)values('$tid','$on')";
$r2=mysql_query($q2)or die("invalid query2");//this query contains error//
It would be great if anyone could help me.
thanks.
You can’t use the result of a call to
mysql_queryas an array, as it is a MySQL resultset. You can usemysql_fetch_assoc()to get the individual rows from that resultset. In your case you need to do something like:You can also use
mysql_insert_id()to get the id of the last inserted record. So instead of doing aSELECTafter theINSERTyou can use that function to retrieve$tid.Furthermore, please read up on SQL injections and spend some time on making your code more secure and formatting (indenting, etc) of your code. There are some other thing wrong with your code that leads me to think you need to do some more research before going on…