jiraiya
jiraiya

Reputation: 997

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?

Upvotes: 7

Views: 12549

Answers (2)

chrisguitarguy
chrisguitarguy

Reputation: 2359

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.

Upvotes: 19

vvzh
vvzh

Reputation: 431

From http://www.php.net/manual/en/pdo.transactions.php:

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. ... if you didn't explicitly commit the transaction, then it is assumed that something went awry, so the rollback is performed for the safety of your data.

Nevertheless, it is a good practice to explicitly rollback a transaction in case of error. See this question for more details: If an PHP PDO transaction fails, must I rollback() explicitely?

Upvotes: 14

Related Questions