F
F
furyon2015-11-02 01:08:03
PHP
furyon, 2015-11-02 01:08:03

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();

How can I be sure that lastInsertId won't throw an error after the entry is added? Or do I need to wrap it in a transaction?
Thank you!
PS
For example, insert was executed, then lastInsertId caused \PDOException and the script stopped working, we tell the user that there is an error, but in fact the record was added. The off-line documentation does not say about errors for lastInsertId, so I don’t know whether to use transactions everywhere for this.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ravshan Abdulaev, 2015-11-02
@ravshanium

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

S
Sergey, 2015-11-02
Protko @Fesor

in general, for good, everything should be wrapped in a transaction (at least one transaction per HTTP request).
The chances that lastInsertId will throw an exception are about zero, but you usually have more than one request, right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question