PDO's lastInsertId for MySQL a race condition?

后端 未结 2 1547
长情又很酷
长情又很酷 2021-01-26 04:36

I\'m writing a PHP class file which pushes data to a MySQL database using PDO. Essentially the file gets hit many times very quickly (creating a new instance of the class each t

相关标签:
2条回答
  • 2021-01-26 04:58

    The issue turned out to be that Chromium's built-in console's network tab does not show the correct information. Showing the ID via console.log() works as expected, and using FireBug for Firefox shows the network activity as expected. I was working under the assumption that the network tab would show the actual network activity, which it does not always.

    0 讨论(0)
  • 2021-01-26 05:19

    MySQL does not return one session's last insert id to another session.

    http://dev.mysql.com/doc/refman/5.6/en/information-functions.html#function_last-insert-id says:

    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.


    Re your comments:

    This has been the behavior of MySQL since the beginning. Returning the last insert ID would be pretty useless if it were susceptible to a race condition, that is if inserts in other sessions could pollute your session.

    One possibility is that you're using persistent connections, because old versions of PHP had a bug that a connection could be given to a new PHP request and grant access to sessions-scoped state from a previous PHP request. In other words, things like locks and transactions and temp tables and user variables and last insert id could survive to a subsequent PHP request. These problems should be resolved in PHP 5.3 with the mysqlnd driver; a persistent connection should be "reset" to an initial state.

    Another possible explanation is that it's really functioning correctly, and you're mistaken in your observations. So I'd suggest testing it carefully and methodically.

    update: according to your answer, this problem had nothing to do with MySQL or PDO or lastInsertId. It sounds like you weren't seeing discrepancies in output of your PHP code at all, you were seeing unexpected numbers in network performance stats in Chrome Dev Tools.

    0 讨论(0)
提交回复
热议问题