PHP 8.1.28 Released!

PDO::rollBack

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

PDO::rollBack Reverte uma transação

Descrição

public PDO::rollBack(): bool

Reverte a transação atual, iniciada por PDO::beginTransaction().

Se o banco de dados foi definido para o modo de confirmação automática, esta função restaurará o modo de confirmação automática após a reversão da transação.

Alguns bancos de dados, incluindo MySQL, emitem automaticamente um COMMIT implícito quando uma instrução DDL (linguagem de definição de banco de dados), como DROP TABLE ou CREATE TABLE, é emitida em uma transação. O COMMIT implícito impedirá que quaisquer outras alterações sejam revertidas dentro do limite da transação.

Parâmetros

Esta função não possui parâmetros.

Valor Retornado

Retorna true em caso de sucesso ou false em caso de falha.

Erros/Exceções

Lança uma exceção PDOException se não houver transação ativa.

Nota: Uma exceção será lançada mesmo quando o atributo PDO::ATTR_ERRMODE não for PDO::ERRMODE_EXCEPTION.

Exemplos

Exemplo #1 Revertendo uma transação

O exemplo a seguir inicia uma transação e emite duas instruções que modificam o banco de dados antes de reverter as alterações. No MySQL, entretanto, a instrução DROP TABLE confirma automaticamente a transação de forma que nenhuma das alterações na transação é revertida.

<?php
/* Inicia uma transação, desligando a auto-confirmação */
$dbh->beginTransaction();

/* Altera esquema e dados do bando */
$sth = $dbh->exec("DROP TABLE fruta");
$sth = $dbh->exec("UPDATE sobremesa
SET nome = 'hamburger'"
);

/* Reconhece o erro e reverte as alterações */
$dbh->rollBack();

/* A conexão do banco agora está de volta no modo de auto-confirmação */
?>

Veja Também

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
16 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