简体   繁体   中英

Trouble using MySQL transactions with loops in PHP

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){

          // loop 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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