In MySQL, some storage engines are transactional (including InnoDB, the default storage engine as of
MySQL 5.5). A transactional engine enables you to perform an operation and then commit it permanently
if it succeeded or roll it back to cancel its effects if an error occurred. PDO provides a mechanism for performing
transactions that is based on the following database-handle methods:
• To start a transaction, invoke beginTransaction() to disable autocommit mode so that database
changes do not take effect immediately.
• To commit a successful transaction or roll back an unsuccessful one, invoke commit() or rollback(),
respectively.
The easiest way to use these methods is to enable PDO exceptions and use try and catch to handle
errors:
$dbh->setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try
{
$dbh->beginTransaction (); # start the transaction
# ... perform database operation ...
$dbh->commit (); # success
}
catch (PDOException $e)
{
print ("Transaction failed: " . $e->getMessage () . "\n");
$dbh->rollback (); # failure
}
For additional paranoia, you can place the rollback() call within a nested try/catch construct so
that if rollback() itself fails and raises another exception, the script doesn’t get terminated.