請注意這個錯誤: https://bugs.php.net/bug.php?id=66528
在使用 MySQL 時,您不能依賴 commit() 的返回值
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)
PDO::commit — 提交事務
此函式沒有參數。
範例 #1 提交一個基本事務
<?php
/* 開始一個事務,關閉自動提交 */
$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();
/* 資料庫連線現在回到自動提交模式 */
?>
範例 #2 提交 DDL 事務
<?php
/* 開始一個事務,關閉自動提交 */
$dbh->beginTransaction();
/* 變更資料庫結構描述 */
$sth = $dbh->exec("DROP TABLE fruit");
/* 提交變更 */
$dbh->commit();
/* 資料庫連線現在回到自動提交模式 */
?>
注意:並非所有資料庫都允許事務對 DDL 陳述式進行操作:有些會產生錯誤,而其他資料庫(包括 MySQL)會在遇到第一個 DDL 陳述式後自動提交事務。