Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is mysql_insert_id safe to use?

Tags:

php

mysql

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?

like image 652
Or Weinberger Avatar asked Feb 21 '11 18:02

Or Weinberger


2 Answers

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.

like image 124
Matthew Avatar answered Sep 24 '22 09:09

Matthew


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.

like image 37
nos Avatar answered Sep 24 '22 09:09

nos