php mysql 回滚,正确使用php mysqli自动提交和回滚

Having trouble with proper usage of mysqli autocommit. Below are the queries.

Table1 and Table3 are InnoDB while Table2 is MyISAM

Values to Table2 and Table3 are inserted properly but values to Table1 are not being stored.

No errors occur while running the code.

$dbconnect->autocommit(false);

$stmt = $dbconnect->prepare("INSERT INTO `table1`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val1,$val2);

$stmt->execute();

$dbconnect->rollback();

$stmt = $dbconnect->prepare("INSERT INTO `table2`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val3,$val4);

$stmt->execute();

$dbconnect->rollback();

$stmt = $dbconnect->prepare("INSERT INTO `table3`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val5,$val6);

$stmt->execute();

$dbconnect->commit();

When and how do you use autocommit(false) and rollback()?

解决方案

You use it when you have a series of sql statements that must be performed together to maintain consistency in your database. Think of calling commit as establishing a save point in a game. Anytime you call rollback you undo everything that was done up to the previous commit.

Imagine a situation where you need to save an invoice in your invoice table, details in your invoice_details table and payments in your payments table. To maintain consistency you need to make sure that these are all done or none of them is done. If you where to add the invoice and the details and then there was a failure on inserting the payment then your database is left in an inconsistent state.

Normally this is accomplished using a try/catch block like this:

try {

$dbconnect->autocommit(false);

$stmt = $dbconnect->prepare("INSERT INTO `invoices`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val1,$val2);

$stmt->execute();

$stmt = $dbconnect->prepare("INSERT INTO `invoice_details`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val3,$val4);

$stmt->execute();

$stmt = $dbconnect->prepare("INSERT INTO `payments`(`col1`,`col2`) VALUES (?,?)");

$stmt->bind_param('ss',$val5,$val6);

$stmt->execute();

$dbconnect->commit();

} catch(Exception $e){

// undo everything that was done in the try block in the case of a failure.

$dbconnect->rollback();

// throw another exception to inform the caller that the insert group failed.

throw new StorageException("I couldn't save the invoice");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值