简体   繁体   English

mysqli事务插入失败回滚失败

[英]Mysqli transaction fail to rollback when insert is failed

I have 3 databases, where I need to create database A, then database B, then create the linking database A_B.我有 3 个数据库,我需要在其中创建数据库 A,然后是数据库 B,然后创建链接数据库 A_B。

I use mysqli transactions in PHP, there is a weird case(this is the first time i use php transactions), where it never rollback when it fails, case like database A fail to insert, but B still created.我在PHP中使用mysqli事务,有一个奇怪的情况(这是我第一次使用php事务),它在失败时永远不会回滚,例如数据库A插入失败,但B仍然创建。 and A_B created incorrectly.和 A_B 创建不正确。

mysqli_begin_transaction($link);
try{

            $sql = "INSERT INTO A (
                     ....)
                    VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?);";
            $stmt = mysqli_prepare($link,$sql);
            mysqli_stmt_bind_param($stmt,"sssssssssssss",
                   ....
            );
            mysqli_stmt_execute($stmt);
            $param_new_A_Rec = mysqli_insert_id($link);
            
            for($i = 0; $i < $tot; $i++){
     
                            
               $sql = "INSERT INTO B (..)
                VALUES
                    (?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?);";

            $stmt = mysqli_prepare($link,$sql);
            mysqli_stmt_bind_param($stmt,"ssssssssssss",
                   ...
            );

            mysqli_stmt_execute($stmt);
            $param_new_B_Rec = mysqli_insert_id($link);
            
            $sql = "INSERT INTO A_B (
                    param_new_A_Rec,
                    param_new_B_Rec,
                     ....                       
              (?,?,?,?,?,?);";
            $stmt = mysqli_prepare($link,$sql);
            mysqli_stmt_bind_param($stmt,"ssssss",
                    ....
            );
            mysqli_stmt_execute($stmt);

            }


            mysqli_commit($link);
            
    }catch (mysqli_sql_exception $exception) {

            mysqli_rollback($link);
          
            throw $exception;
            
    }

Why if A failed, it never hit the rollback() and it created the incorrect A_B and B data?为什么如果 A 失败了,它永远不会命中 rollback() 并且它创建了不正确的 A_B 和 B 数据? Did I miss anything here?我在这里错过了什么吗? any help would be greatly appreciated!任何帮助将不胜感激!

In fact, I need to add this事实上,我需要添加这个

"mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);" "mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);"

Now it is catching the invalid use case:现在它正在捕获无效的用例:

PHP Fatal error: Uncaught mysqli_sql_exception: Incorrect integer value: '' for column 'boolean_X' at row 1 in yourFile.php PHP 致命错误:未捕获的 mysqli_sql_exception:不正确的整数值:''for 'boolean_X' 列在 yourFile.php 的第 1 行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM