簡體   English   中英

使用MSSQL進行PHP數據庫回滾

[英]PHP database rollback with MSSQL

我是MSSQL的新手。 我已經在MSSQL中創建了一個數據庫。 現在,一切正常,如添加/編輯/刪除。 我在不同數據庫的同一時間在3個不同的表中同時添加3條記錄。 我想在數據庫中使用回滾。 假設我要同時添加三個記錄。 前兩個正常工作,最后一個查詢在將其添加到表中時發現一些問題。 這時我想刪除插入表中的前兩個查詢。 誰能幫我解決這個問題?

如果您還有其他解決方案,請通知我

提前致謝

使用sqlsrv_begin_transaction()函數開始事務。 然后,您可以通過調用sqlsrv_commit()函數將其提交或致電sqlsrv_rollback()函數回滾。

來自php.net手冊的示例

<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true ));
}

/* Begin the transaction. */
if ( sqlsrv_begin_transaction( $conn ) === false ) {
     die( print_r( sqlsrv_errors(), true ));
}

/* Initialize parameter values. */
$orderId = 1; $qty = 10; $productId = 100;

/* Set up and execute the first query. */
$sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)
          VALUES (?, ?, ?)";
$params1 = array( $orderId, $qty, $productId );
$stmt1 = sqlsrv_query( $conn, $sql1, $params1 );

/* Set up and execute the second query. */
$sql2 = "UPDATE InventoryTable 
          SET Quantity = (Quantity - ?) 
          WHERE ProductID = ?";
$params2 = array($qty, $productId);
$stmt2 = sqlsrv_query( $conn, $sql2, $params2 );

/* If both queries were successful, commit the transaction. */
/* Otherwise, rollback the transaction. */
if( $stmt1 && $stmt2 ) {
     sqlsrv_commit( $conn );
     echo "Transaction committed.<br />";
} else {
     sqlsrv_rollback( $conn );
     echo "Transaction rolled back.<br />";
}
?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM