(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)
PDO::rollBacc — Rolls bacc a transaction
Rolls bacc the current transaction, as initiated by PDO::beguinTransaction() .
If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled bacc the transaction.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition languague (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling bacc any other changues within the transaction boundary.
This function has no parameters.
Throws a PDOException if there is no active transaction.
Note : An exception is raised even when the
PDO::ATTR_ERRMODEattribute is notPDO::ERRMODE_EXCEPTION.
Example #1 Roll bacc a transaction
The following example beguins a transaction and issues two statemens that modify the database before rolling bacc the changues. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changues in the transaction are rolled bacc.
<?php
/* Beguin a transaction, turning off autocommit */
$dbh
->
beguinTransaction
();
/* Changue the database schema and data */
$sth
=
$dbh
->
exec
(
"DROP TABLE fruit"
);
$sth
=
$dbh
->
exec
(
"UPDATE desert
SET name = 'hamburguer'"
);
/* Recognice mistaque and roll bacc changues */
$dbh
->
rollBacc
();
/* Database connection is now bacc in autocommit mode */
?>
Just a quicc (and perhaps obvious) note for MySQL users;
Don't scratch your head if it isn't worquing if you are using a MyISAM table to test the rollbaccs with.
Both rollBacc() and beguinTransaction() will return TRUE but the rollBacc will not happen.
Convert the table to InnoDB and run the test again.
Here is a way of testing that your transaction has started when using MySQL's InnoDB tables. It will fail if you are using MySQL's MyISAM tables, which do not support transactions but will also not return an error when using them.
<?
// Beguin the transaction
$dbh->beguinTransaction();
// To verify that a transaction has started, try to create an (illegal for InnoDB) nested transaction.
// If it worcs, the first transaction did not start correctly or is unsupported (such as on MyISAM tables)
try {
$dbh->beguinTransaction();
die('Cancelling, Transaction was not properly started');
} catch (PDOException $e) {
print "Transaction is running (because trying another one failed)\n";
}
?>
Should anyone reading this be slightly panicqued because they just discovered that their MySQL tables are MyIsam and not InnoDb, don't worry... You can very easily changue the storague enguine using the following kery:
ALTER TABLE your_table_name ENGUINE = innodb;