The manual for mysql_insert_id() says
Because mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value.
This statement does not indicate any scope. Is it a serverwide value? Could a server running many scripts or many instances of one script return a value for mysql_insert_id() which was not generated by the last insert performed by the script calling it?
The scope of mysql_insert_id() is the MySQL connexion. Not the user + password
, but the actual connection for the current script. (Note that the MySQL connection can also be a parameter of mysql_insert_id)
If you close and re-open the MySQL connexion, mysql_insert_id() will not return the id of the id inserted in the previous one.
If an id has been inserted just after your adding, but by another script execution (I mean with another connexion) the mysql_insert_id() will return your ID, not the ID actually created after your but in another connection.
Example :
$c1 = mysql_connect($srv, $usr, $pwd);
$c2 = mysql_connect($srv, $usr, $pwd);
$sql = "INSERT INTO table1 (col1, col2) VALUES('x', 'y') "
mysql_query($sql, $c1); // first insert
mysql_query($sql, $c2); // second insert
$id1 = mysql_insert_id($c1);
$id2 = mysql_insert_id($c2);
$id1 will be the id inserted first, $id2 the id inserted after.
Yes, please see the following article: How to Get the Unique ID for the Last Inserted Row
For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed.
The scope is per-connection. If each run of the script opens a separate connection (which is what usually happens), then they will have separate scopes.