Reputation: 443
I am using this query to insert data into two different tables:
$query1="INSERT INTO node (cid, title) VALUES('$cid','$title')";
$query2="INSERT INTO location (nid, street, city, state) VALUES(LAST_INSERT_ID(),'$address', '$city','$state')";
$result = FALSE;
if (mysql_query('BEGIN')) {
if (mysql_query($query1) &&
mysql_query($query2))
$result = mysql_query('COMMIT'); // both queries looked OK, save
else
mysql_query('ROLLBACK'); // problems with queries, no changes
}
basically, the first query throws the data into the node table which in turn increments a NID field. This NID is used in the second query (my location table).
Now I have changed my website a bit and I also want to insert that same NID into a 3rd table. The problem is the second query (location table) also has an ID column (LID) that auto_increments as well, so if I try to use last_insert_ID it will just give me the LID and not the NID.
I was thinking I could do a 3rd query outside of the transaction where I would query the database and grab the correct nid, but I want to keep it inside of a transaction to prevent any mixups. Any ideas?
Upvotes: 1
Views: 2981
Reputation: 30555
The function LAST_INSERT_ID()
is only guaranteed to work once.
Best practice is to capture this value in your code directly after the query you want it after, either with SELECT LAST_INSERT_ID()
or by using mysqli_insert_id()
. Then you can insert it into later queries with impunity.
Upvotes: 1