Is mysql_insert_id safe to use?
According to the PHP documentation, mysql_insert_id
takes the last inserted id from the mysql table.
My question is, if I have a website that inserts more than 2 rows per second to the DB, can I use the mysql_insert_id
and get the correct ID I am referring to in the INSERT
query a line before?
Solution 1:
From the MySQL manual:
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.
Short version: it is safe to use.
Solution 2:
mysql_insert_id gives you the insert id of the most recent INSERT statement on the connection you give it.
If you call this immediatly after your insert, on the same mysql connection, you get the inserted id matching that insert statement, independantly of any other inserts going on in the mean time.