问题
How reliable is mysql_insert_id()
in a competitive condition? I mean when multiple users are inserting data at the same time, will this function return the true ID or it will return other user's inserted data ID?
The table engine is MyISAM.
回答1:
mysql_insert_id
is completely multi-user safe.It is entirely relies upon the database connection, and you can only have one user per connection....So, as per your question, it returns true id....
From MySql documentation,
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.
回答2:
imho even when multiple users are inserting..it will be sequential in your program execution.
from php.net
"mysql_insert_id() acts on the last performed query, be sure to call mysql_insert_id() immediately after the query that generates the value. "
Also
Use of this extension is discouraged. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
mysqli_insert_id()
PDO::lastInsertId()
You may also check this link from dev.mysql where it states that
"The value of mysql_insert_id() is affected only by statements issued within the current client connection. It is not affected by statements issued by other clients. "
来源:https://stackoverflow.com/questions/11920804/mysql-insert-id-issue-in-concurrency-data-inserting