Answer the question
In order to leave comments, you need to log in
Should lastInsertId() be wrapped in a transaction?
Hello!
Let's say I insert a record and I need to get its ID, it's simple:
$STM = $PDO->prepare('INSERT INTO bonuses (date,user_id) VALUES (?,?)');
$STM->execute([time(), 1]);
$id = $PDO->lastInsertId();
Answer the question
In order to leave comments, you need to log in
I don't think it's desirable to use PDO::LastInsertId(), especially if a persistent connection is used. INSERT has a RETURNING option - returns the id of the added entry, I think this is the best alternative. and yes inserting a row and getting its id should be in the same transaction.
php.net/manual/en/pdo.lastinsertid.php#102614
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question