I am just refining some code on one of my applications which I converted from using PHP ADODB library to PDO lately. In adodb once you launched a transaction it automatically rolled back if any exception should arise with queries between the begin and commit commands.
Does PDO also do this. If a method which has a query it it fails between a begin and commit in PDO will the trsaction automatically rollback or does it need to be implicitly called?
You have to call rollback (and commit) yourself, PDO
won't do it for you. Something like this:
$pdo = new \PDO(/* ... */);
$pdo->beginTransaction();
try {
// do stuff..
} catch(\Throwable $e) { // use \Exception in PHP < 7.0
$pdo->rollBack();
throw $e;
}
$pdo->commit();
PDO will rollback any open transactions when a script ends, however.
When the script ends or when a connection is about to be closed, if you have an outstanding transaction, PDO will automatically roll it back.
So the transaction will probably get rolled back depending on your application (maybe you have an even listener some place that's going to commit for you?). It's probably a good idea to do an explicit rollback right near where the exception happened.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With