mysql_insert_id issue in concurrency data insertin

2019-01-15 20:11发布

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.

2条回答
Evening l夕情丶
2楼-- · 2019-01-15 20:45

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.

查看更多
beautiful°
3楼-- · 2019-01-15 20:48

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. "

查看更多
登录 后发表回答