PDO::beginTransaction

PHP PDO 参考手册PHP PDO Reference Manual

PDO::beginTransaction Starts a transaction (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)


Description

Syntax

bool PDO::beginTransaction ( void )

Turns off auto-commit mode. While auto-commit mode is turned off, changes made to the database through the PDO object instance will not be committed until the transaction is ended by calling PDO::commit().

Calling PDO::rollBack() will roll back changes made to the database and return the database connection to auto-commit mode.

Some databases, including MySQL, automatically issue an implicit transaction commit when a DDL statement such as DROP TABLE or CREATE TABLE is issued.

This implicit commit will prevent you from rolling back any other changes within the transaction scope.


Return Values

Returns TRUE on success, or FALSE on failure.

Examples

Rolling Back a Transaction

The following example starts a transaction and issues two statements that modify the database before rolling back the changes.

However, in MySQL, the DROP TABLE statement automatically commits the transaction, so any changes within this transaction will not be rolled back.

<?php
/* 开始一个事务,关闭自动提交 */
$dbh->beginTransaction();

/*  更改数据库架构及数据 */
$sth = $dbh->exec("DROP TABLE fruit");
$sth = $dbh->exec("UPDATE dessert
    SET name = 'hamburger'");

/*  识别出错误并回滚更改 */
$dbh->rollBack();

/* 数据库连接现在返回到自动提交模式 */
?>

PHP PDO 参考手册PHP PDO Reference Manual

Other Extensions