函式名:db2_commit() 適用版本:PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8
用法:db2_commit(resource $connection): bool
說明:db2_commit() 函式用於提交當前資料庫連線所處的事務。
引數:
- $connection:一個有效的資料庫連線資源。
返回值:如果事務成功提交,則返回 true;否則返回 false。
示例:
// 建立資料庫連線
$database = 'SAMPLE';
$user = 'username';
$password = 'password';
$conn = db2_connect($database, $user, $password);
// 開始事務
db2_autocommit($conn, false);
// 執行一些資料庫操作
$sql = "INSERT INTO employees (name, age) VALUES ('John Doe', 30)";
$stmt = db2_prepare($conn, $sql);
db2_execute($stmt);
// 檢查是否有錯誤
if (db2_stmt_error($stmt)) {
// 回滾事務
db2_rollback($conn);
die("An error occurred during database operation. Transaction rolled back.");
}
// 提交事務
if (db2_commit($conn)) {
echo "Transaction committed successfully.";
} else {
echo "Failed to commit transaction.";
}
// 關閉資料庫連線
db2_close($conn);
在上述示例中,首先我們建立了一個資料庫連線 $conn
,然後透過 db2_autocommit()
函式將自動提交事務的選項關閉,將事務的控制權移交給程式碼。接下來執行了一個插入操作,並透過 db2_stmt_error()
檢查是否有錯誤發生。如果有錯誤,則透過 db2_rollback()
函式回滾事務,否則透過 db2_commit()
函式提交事務。
最後,我們關閉了資料庫連線 $conn
。