开发者

Trouble using MySQL transactions with loops in PHP

开发者 https://www.devze.com 2023-01-09 00:15 出处:网络
I am trying to set up a MySQL transaction such that I can loop through a bunch of queries (see below) and if any of them fail, rollback all of the changes. I am finding however that if one fails, not

I am trying to set up a MySQL transaction such that I can loop through a bunch of queries (see below) and if any of them fail, rollback all of the changes. I am finding however that if one fails, not all of the queries are rolled back. Am I doing anything wrong here?

mysql_query("START TRANSACTION");

     foreach($array1 as $arr){

          // l开发者_StackOverflow社区oop SQL query

          if(mysql_error()){
               $failed = "...";
          }
     }


     foreach($array2 as $arr){

          // loop SQL query

          if(mysql_error()){
               $failed = "...";
          }
     }

     if(isset($failed)){
          mysql_query("ROLLBACK");
     } else {
          mysql_query("COMMIT");
     }

Thanks!


The reason is that if a query fails (due to error), the transaction is automatically rolled back and terminated. So you should stop looping if a query fails, because anything executing after the failed query will autocommit (Or at least be in another transaction if AUTOCOMMIT is off)...


Are you using a transaction-safe table type? The default MyISAM does not support transactions, I recommend using InnoDB.

0

精彩评论

暂无评论...
验证码 换一张
取 消