PDO::rollBack
(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
PDO::rollBack — Rolls back a transaction
Description
Rolls back the current transaction, as initiated by PDO::beginTransaction(). A PDOException will be thrown if no transaction is active.
If the database was set to autocommit mode, this function will restore autocommit mode after it has rolled back the transaction.
Some databases, including MySQL, automatically issue an implicit COMMIT when a database definition language (DDL) statement such as DROP TABLE or CREATE TABLE is issued within a transaction. The implicit COMMIT will prevent you from rolling back any other changes within the transaction boundary.
Return Values
Returns TRUE
on success or FALSE
on failure.
Examples
Example #1 Roll back a transaction
The following example begins a transaction and issues two statements that modify the database before rolling back the changes. On MySQL, however, the DROP TABLE statement automatically commits the transaction so that none of the changes in the transaction are rolled back.
<?php
/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();
/* Change the database schema and data */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
SET name = 'hamburger'");
/* Recognize mistake and roll back changes */
$dbh->rollBack();
/* Database connection is now back in autocommit mode */
?>
See Also
- PDO::beginTransaction() - Initiates a transaction
- PDO::commit() - Commits a transaction
- Transactions and auto-commit
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Уровни абстракции
- Объекты данных PHP
- Функция PDO::beginTransaction() - Инициализация транзакции
- Функция PDO::commit() - Фиксирует транзакцию
- Функция PDO::__construct() - Создает экземпляр PDO, предоставляющий соединение с базой данных
- Функция PDO::errorCode() - Возвращает код SQLSTATE результата последней операции с базой данных
- PDO::errorInfo
- PDO::exec
- Функция PDO::getAttribute() - Получить атрибут соеденения с базой данных
- Функция PDO::getAvailableDrivers() - Возвращает массив доступных драйверов PDO
- Функция PDO::inTransaction() - Проверяет, есть ли внутри транзакция
- Функция PDO::lastInsertId() - Возвращает ID последней вставленной строки или последовательное значение
- PDO::prepare
- PDO::query
- Функция PDO::quote() - Заключает строку в кавычки для использования в запросе
- Функция PDO::rollBack() - Откат транзакции
- Функция PDO::setAttribute() - Присвоение атрибута
Коментарии
Just a quick (and perhaps obvious) note for MySQL users;
Don't scratch your head if it isn't working if you are using a MyISAM table to test the rollbacks with.
Both rollBack() and beginTransaction() will return TRUE but the rollBack 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.
<?
// Begin the transaction
$dbh->beginTransaction();
// To verify that a transaction has started, try to create an (illegal for InnoDB) nested transaction.
// If it works, the first transaction did not start correctly or is unsupported (such as on MyISAM tables)
try {
$dbh->beginTransaction();
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 panicked because they just discovered that their MySQL tables are MyIsam and not InnoDb, don't worry... You can very easily change the storage engine using the following query:
ALTER TABLE your_table_name ENGINE = innodb;