This question already has an answer here:
I've got a page calling a script via AJAX which could be asynchronously called multiple times simultaneously from the same parent page. This script uses require_once to access a configuration script with the database handler. Will the script call a unique instance of this handler each time, or if multiple copies are open will they all be using the same instance and causing undesirable results when I attempt to get the ID of the last insert from that instance of the script?
Just to be clear, this is the command I'm referencing:
$DBH->lastInsertId()
Thanks!
</div>
As noted in the documentation:
Note: This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.
The documentation says
This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even support the notion of auto-increment fields or sequences.
That being said, I've never had a problem using lastInsertId
with MySQL. It's always worked.
This ostensibly wraps a call to MySQL's LAST_INSERT_ID()
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.
i.e. it should be safe to use even if you are facing frequent requests.
$DBH->lastInsertId()
retrieves, in case of MySQL, the result of last_insert_id()
function.
The last_insert_id()
is session based, which means that if you have 2 PHP scripts running, you will only get the ones last_insert_id
that were generated by each script.
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.