1. To support transactions within the program, the first connected database and data table must support the transaction MySQL for example:
Database InnoDB Support Transactions
Data table Support transactions: InnoDB support Transaction
2. Framework thinkphp Support Transaction code
Public functionTestrollback () {$model 1= D (' Item ');$model 2= D (' vote ');$model 1-Starttrans ();$res 1=$model 1->where (' id = 5 ')Delete ();$res 2=$model 2->where (' id = 2 ')Delete ();d UMP ($res 1);d UMP ($res 2);if($res 1&&$res 2){$model 1->commit ();//only $res1 and $res 2 are successful in performing the above database operationsDump ("Commit");}Else{$model 1->rollback ();//condition not satisfied, rollbackDump ("rollback");} Dump ("Over");Exit;}
3. Original PHP Code Transaction instance
Method One: Only support the database and the data table are InnoDB cases
Public functionRollbackoriginal1 () {$conn=mysql_connect(' 127.0.0.1 ', ' Summerzi ', ' Summerzi ') or die(' DB connection failed! '); mysql_select_db(' Summer ',$conn); mysql_query(' Set names ' GBK "'); mysql_query(' BEGIN '); $sql 1= "INSERT into ' summer_userdata ' (' uid ', ' type ', ' target_id ') VALUES (41,1,233);"; $sql 2= "INSERT into ' summer_userdata ' (' uid ', ' type ', ' target_id ') VALUES (fdfd,2,235);"; $res 1=mysql_query($sql 1); $res 2=mysql_query($sql 2); Dump ($sql 1); Dump ($sql 2); Dump ($res 1); Dump ($res 2); if($res 1&&$res 2){ mysql_query(' COMMIT '); Dump (' Commit success! '); }Else{ mysql_query(' ROLLBACK '); Dump (' Commit failed, rollback! '); } mysql_query(' END '); }
Method Two: (Note: The table locking method is available for MyISAM engine databases that do not support transactions)
Public functionRollbackoriginal2 () {$conn=mysql_connect(' 127.0.0.1 ', ' Summerzi ', ' Summerzi ') or die(' DB connection failed! '); mysql_select_db(' Summer ',$conn); mysql_query(' Set names ' GBK "'); mysql_query(' SET autocommit=0 ');////Set MySQL not to submit automatically, you need to commit the commit statement by yourself $sql 1= "INSERT into ' summer_userdata ' (' uid ', ' type ', ' target_id ') VALUES (41,1,233);"; $sql 2= "INSERT into ' summer_userdata ' (' uid ', ' type ', ' target_id ') VALUES (44,2,235);"; //mysql_query ("Lock TABLES ' Hmbl_userdata ' WRITE");//Lock Table $res 1=mysql_query($sql 1); $res 2=mysql_query($sql 2); Dump ($sql 1); Dump ($sql 2); Dump ($res 1); Dump ($res 2); //mysql_query ("UNLOCK TABLES");//Unlocked if($res 1&&$res 2){ mysql_query(' COMMIT '); Dump (' Commit success! '); }Else{ mysql_query(' ROLLBACK '); Dump (' Commit failed, rollback! '); } mysql_query("SET autocommit=1"); mysql_query(' END '); }
php + MySQL transaction processing is relatively simple, involving multiple data operations in the business, you can consider using transaction processing
thinkphp transaction rollback processing and the original PHP transaction rollback instance