Okay first of all, I admit I took elements from this question here: How to get result of Insert
Anyways, I have two tables and in the second table there is a foreign key column for table A.
Table A:
id Name
----------------
1 Name1
2 Name2
Table B:
id Name Parent
-------------------------
1 John 1
The problem is I need the ID of anything inserted into table A, to use for the foreign key in table B.
The accepted answer was the following bit of code in PHP:
$res = mysql_query('SELECT LAST_INSERT_ID()');
$row = mysql_fetch_array($res);
$lastInsertId = $row[0];
I’ve seen similar code elsewhere, but isn’t there a synchronization issue here? Couldn’t it be possible for a different SQL insert to occur right in between one SQL insert and getting the ID with SELECT LAST_INSERT_ID()? Therefore ending up with the wrong ID?
Thanks,
Sam
Either using the function
mysql_insert_id()or the method you described in your question are reliable and concurrency safe. Both methods use the active connection, the concurrency issue you’re pointing to is anticipated and dealt with internally.If you Google search for this question, you’ll see some people advocate using ‘SELECT MAX(id) FROM some_table`, which DOES have the concurrency problem you’re worried about and should not be used. Either of the aforementioned two methods don’t have this problem and are equally “best practice”.
You can read some more discussion about the MySQL function here: http://dev.mysql.com/tech-resources/articles/storage-engine/part_3.html
The relevant bit from that article:
In the PHP documents, you can see that
mysql_insert_id()takes a connection as an argument, or it assumes the last opened one: http://php.net/manual/en/function.mysql-insert-id.php