Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top