PHP 8.3.4 Released!

PDO::rollBack

(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)

PDO::rollBack Revierte una transacción

Descripción

public PDO::rollBack(): bool

Revierte la transacción actual, que fue iniciada por PDO::beginTransaction().

Si la base de datos se estableció al modo 'autocommit', esta función restablecerá el modo 'autocommit' después de haber revertido la transacción.

Algunas bases de datos, incluyendo MySQL, ejecutan un COMMIT implícito cuando una sentencia de lenguaje de definición de base de datos (DDL), como DROP TABLE o CREATE TABLE, se ejecuta dentro de una transacción. El COMMIT implícito pevendrá de revertir cualquier otro cambio dentro de los límites de la transacción.

Valores devueltos

Devuelve true en caso de éxito o false en caso de error.

Errores/Excepciones

Lanza una PDOException si no hay ninguna transacción activa.

Nota: Se emite una excepción inclusi cuando el atributo PDO::ATTR_ERRMODE no es PDO::ERRMODE_EXCEPTION.

Ejemplos

Ejemplo #1 Revertir una transacción

El siguiente ejemplo comienza una transacción y ejecuta dos sentencias que modifican la base de datos antes de revertir los cambios. En MySQL, sin embargo, la sentencia DROP TABLE consigna automáticamente la transacción, por lo que no son revertidos ninguno de los cambios en la transacción.

<?php
/* Comenzar una transacción, desactivando el modo 'autocommit' */
$gbd->beginTransaction();

/* Cambiar el esquema y los datos de la base de datos */
$sth = $gbd->exec("DROP TABLE fruit");
$sth = $gbd->exec("UPDATE dessert
SET name = 'hamburger'"
);

/* Reconocer el error y revertir los cambios */
$gbd->rollBack();

/* Ahora la conexión a la base de datos a vuelto al modo 'autocommit' */
?>

Ver también

add a note

User Contributed Notes 4 notes

up
53
JonasJ
16 years ago
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.
up
11
brian at diamondsea dot com
15 years ago
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";
}
?>
up
5
Petros Giakouvakis
13 years ago
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;
up
-7
linfo2003 at libero dot it
16 years ago
Since "It is an error to call this method if no transaction is active", it could be useful (even if not indispensable) to have a method which returns true if a transaction is active.

try {
$dbh->beginTransaction();
...
} catch (PDOException $e) {
if ($dbh->isTransactionActive()) // this function does NOT exist
$dbh->rollBack();
...
}

In the meanwhile, I'm using this code:

...
} catch (PDOException $e) {
try { $dbh->rollBack(); } catch (Exception $e2) {}
...
}

It's not so chic, but it works fine.
To Top