dtnrsmi824877 2014-01-22 05:45
浏览 84
已采纳

正确使用php mysqli autocommit和rollback

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()?

  • 写回答

1条回答 默认 最新

  • dsy1971 2014-01-22 06:08
    关注

    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");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器