undefinedfix
Sign in

MySQL statement, transaction processing rollback problem.

victorm1710 edited in Fri, 06 Nov 2020

mysql_ query("BEGIN");

$ck_ id = M('ods')->add($public);

foreach ($datas as $k => $val) {

 $saveData = M('odo')->add($val);

}

Because of the data inserted into the ODO table, I use the foreach loop to insert multiple pieces of data. How can I judge that all of these data have been successfully inserted? If one of them fails, roll back it.

if($ck_ id && $saveData){

              mysql_query("COMMIT");
             $this->success("数据提交成功","__GROUP__/Warehouse/outbound");  
        }else{
             mysql_query("ROLLBACK");
            $this->error("数据回滚,请重新提交");
       }

mysql_ Query ("end"); if five pieces of data are cycled, how can you judge that $savedata knows that all five pieces of data have been inserted successfully? Do you need to make a counter? Define a variable $count = 0 before the loop, and $count + 1 for each successful insertion;

Such as $count = 0; foreach ($data as $k = > $VAL){

 $saveData = M('odo')->add($val);
 if($saveData>0) {
    $count++;
 }

}if($ck_ ID & $count = = 5) {rollback processing....}

Is this ok? Who has a good method

4 Replies
suxbr
commented on Sat, 07 Nov 2020

Usually, the transaction processing is written in the try catch structure. When add() returns an error and throws an exception directly, the exception can be caught in the catch, and then the corresponding rollback and logging can be done. In addition, you can't write your open transaction like that. The underlying database driver of the framework is not necessarily written with MySQL extension function, and MySQL extension function is no longer recommended, but with mysqli or PDO. ThinkPHP has corresponding database operation methods, so its encapsulated methods should be used.

rhhfc
commented on Sat, 07 Nov 2020

Your method is OK, or it can be changed to have an unsuccessful roll back and jump out of the loop.

dancesWithCycles
commented on Sat, 07 Nov 2020

Mysqli seems to have a rollback interface.

pg7733
commented on Sat, 07 Nov 2020

Determine whether the number of rows will be affected after saving. If not, roll back

lock This question has been locked and the reply function has been disabled.