Reliable or not PDO lastInsertId() when using transactions

狂风中的少年 提交于 2020-01-30 07:00:05

问题


I use PDO transaction

try {
    DB::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    DB::$db->beginTransaction();

    $db->prepare( insert query );
    $db->execute();

    $last_insert_id = $db->lastInsertId();

    ...
    ...

Multiple concurrent requests are expected on this script.

Question: is it possible that lastInsertId() return incorrect value for the user, who actually inserted the row?

(by "incorrect value" i mean: id that is inserted by some other user).


回答1:


You're safe. The ID you get will be the correct one.

PDO's lastInsertId (and mysql's last_insert_id to which your PDO delegates the call in this case) gives the last autogenerated ID on a per-connection basis.

From mysql's 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.

Concurrent connections will not compromise the integrity of the returned id. And as you mention in your comment, transactions have no bearing on this. Just don't forget to commit!

I'll also mention there is the unlikely possibility, if you run multiple statements on the same connection, and if your execute method throws an exception which isnt handled correctly, that lastInsertId could return the id of the last successful insert on that connection. But it can never return an ID from another user's query.



来源:https://stackoverflow.com/questions/22126830/reliable-or-not-pdo-lastinsertid-when-using-transactions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!