Reputation: 53
so I have 2 queries that I'm trying to execute in php. However I get an error. The first id in the first query is auto inc, the second one id in the second query isnt auto inc but it is connected via foreign key to the first one. I want to capture the same id for both of them when the query executes. however this error pops up.
#1452 - Cannot add or update a child row: a foreign key constraint fails (
eangele
.relationships
, CONSTRAINTrelationships_ibfk_3
FOREIGN KEY (id
) REFERENCESnodes
(id
) ON DELETE NO ACTION ON UPDATE NO ACTION)
$query = "insert into nodes(id,name,color,type,thumb)".
"values('','$nodename','#EBB056','star','$thumbFile')";
$result = $db -> Execute($query);
$querytwo = "insert into relationships(id,goingto,data)".
"values(LAST_INSERT_ID(),'$category','')";
$resulttwo = $db -> Execute($querytwo);
Upvotes: 1
Views: 407
Reputation: 191749
'LAST_INSERT_ID()'
is a literal string. You want to use it without the apostrophes as just values(LAST_INSERT_ID(),
.
In case that doesn't work, you can use the php function corresponding to the MySQL API you are using to get the last insert ID. I've also only seen it used with SELECT
. I assume it will work with VALUES
like that, but in case it doesn't you can always do an insert/select:
INSERT INTO relationships(id, goingto, data)
SELECT LAST_INSERT_ID(), ?, ''
Your queries are vulnerable to injection. You should parameterize them.
Upvotes: 2