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

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

Is this ok? Who has a good method

4 Replies
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.

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.

commented on Sat, 07 Nov 2020

Mysqli seems to have a rollback interface.

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.