Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO transaction automatic rollBack

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?

like image 932
jiraiya Avatar asked May 18 '13 19:05

jiraiya


Video Answer


1 Answers

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.

like image 139
chrisguitarguy Avatar answered Sep 29 '22 11:09

chrisguitarguy