简体   繁体   中英

insert LAST_INSERT_ID issue

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 , CONSTRAINT relationships_ibfk_3 FOREIGN KEY ( id ) REFERENCES nodes ( 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);

'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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM