简体   繁体   English

使用MSSQL进行PHP数据库回滚

[英]PHP database rollback with MSSQL

I am new in the MSSQL. 我是MSSQL的新手。 i have create a database in MSSQL. 我已经在MSSQL中创建了一个数据库。 Now all is working fine like add/edit/delete. 现在,一切正常,如添加/编辑/删除。 i am adding 3 record in 3 different table at the same time in same of different database. 我在不同数据库的同一时间在3个不同的表中同时添加3条记录。 I want to use Rollback in the database. 我想在数据库中使用回滚。 Suppose i am adding three record at the same time. 假设我要同时添加三个记录。 First two work properly and last query find some issue in adding it in the table. 前两个正常工作,最后一个查询在将其添加到表中时发现一些问题。 At this time i want to remove the first two query which is inserted in the table. 这时我想删除插入表中的前两个查询。 can anyone help me for this issue ? 谁能帮我解决这个问题?

if you have another option to solve this issue then let me know 如果您还有其他解决方案,请通知我

Thanks in advance 提前致谢

Use sqlsrv_begin_transaction() function to begin a transaction. 使用sqlsrv_begin_transaction()函数开始事务。 Then, you can either commit it by calling sqlsrv_commit() function or roll it back by calling sqlsrv_rollback() function. 然后,您可以通过调用sqlsrv_commit()函数将其提交或致电sqlsrv_rollback()函数回滚。

Example from php.net manual 来自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