PDO::commit

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

PDO::commit 提交一個事務

說明

PDO::commit(): bool

提交一個事務,數(shù)據(jù)庫連接返回到自動提交模式直到下次調(diào)用 PDO::beginTransaction() 開始一個新的事務為止。

返回值

成功時返回 true, 或者在失敗時返回 false。

范例

示例 #1 提交一個基礎事務

<?php
/* 開始一個事務,關(guān)閉自動提交 */
$dbh->beginTransaction();

/* 在全有或全無的基礎上插入多行記錄(要么全部插入,要么全部不插入) */
$sql 'INSERT INTO fruit
    (name, colour, calories)
    VALUES (?, ?, ?)'
;

$sth $dbh->prepare($sql);

foreach (
$fruits as $fruit) {
    
$sth->execute(array(
        
$fruit->name,
        
$fruit->colour,
        
$fruit->calories,
    ));
}

/* 提交更改 */
$dbh->commit();

/* 現(xiàn)在數(shù)據(jù)庫連接返回到自動提交模式 */
?>

示例 #2 提交一個DDL事務

<?php
/*  開始一個事務,關(guān)閉自動提交 */
$dbh->beginTransaction();

/* Change the database schema */
$sth $dbh->exec("DROP TABLE fruit");

/* 更改數(shù)據(jù)庫架構(gòu) */
$dbh->commit();

/* 現(xiàn)在數(shù)據(jù)庫連接返回到自動提交模式 */
?>

注意: 并不是所有數(shù)據(jù)庫都允許使用DDL語句進行事務操作:有些會產(chǎn)生錯誤,而其他一些(包括MySQL)會在遇到第一個DDL語句后就自動提交事務。

參見