A transaction is a case of multiple modifications to a database, either a successful or a complete failure, a partial modification, or a partial modification failure.
PHP operation MySQL database to implement transaction submission, you should pay attention to the following:
1, the database table storage engine type is set to InnoDB. The default MySQL table takes the MyISAM engine and does not support transactions, so the following statement changes are used:
mysql> ALTER TABLE ' table_name ' engine=innodb;
2,pdo object set to set Errmode to exception, otherwise 16th row SQL execution error, the statement will not jump to the catch segment to rollback, but continue to execute down until commit.
1 Try {2 $pdo=NewPDO ($dsn,$user,$pass);//Initializes a PDO object, which is the creation of a database connection object $pdo3 $pdo->setattribute (Pdo::attr_errmode, PDO::errmode_exception);4 $pdo->begintransaction ();//Open Transaction5 $query= "correct statement";6 $result=$pdo->prepare ($query);7 8 if($result-Execute ()) {9 Echo"Data added successfully!" ";Ten}Else{ One Echo"Data addition failed!" "; A } - - the $query= "wrong statement"; - $result=$pdo->prepare ($query); - - if($result-Execute ()) { + Echo"Data added successfully!" "; -}Else{ + Echo"Data addition failed!" "; A } at - - $pdo->commit ();//commit operation for transaction execution -}Catch(pdoexception$e) { - die("error!:".)$e->getmessage (). "<br/>"); - $pdo->rollback ();//performing a rollback of a transaction in}
How does MySQL implement transactional commit in PHP?