PDO Transaction Processing
2014-9-3 10:44:19 by jiancaigege
==========================================
Summary: Multiple SQL operations (add, delete, modify, and delete operations) are used as one operation unit, either successful or failed.
Transactions are not required for a single piece of data.
The operated table must be an InnoDB table (transactions supported)
Common MySQL table types: MyISAM (non-transactional) Fast addition, deletion, and modification, and high InnoDB (transaction) Security
Change the table type to InnoDB.
Mysql> alter table Stu engine = InnoDB;
Usage:
Add the following format based on PDO preprocessing:
1 try {2 3 $ M-> begintransaction (); // enable transaction processing 4 5 // PDO preprocessing and execution statement... 6 7 $ M-> commit (); // submit transaction 8 9} catch (pdoexception $ e) {10 11 $ M-> rollback (); // transaction rollback 12 // related error handling 13}
Example:
1 $ M = new PDO ($ DSN, $ user, $ PWD); 2 $ M-> setattribute (PDO: attr_errmode, PDO: errmode_exception ); 3 try {4 $ M-> begintransaction (); // enable transaction processing 5 6 $ stmt = $ M-> prepare ("insert into Stu (name, sex, age, classid) values (?,?,?,?) "); 7 $ DATA = array (8 array (" user1 "," lamp76 "), 9 array (" user2 "," lamp76 "), 10 array ("user3", "lamp76") 11); 12 foreach ($ data as $ v) {13 $ stmt-> execute ($ V ); 14 echo $ M-> lastinsertid (); 15} 16 $ M-> commit (); 17 echo "submitted successfully! "; 18} catch (pdoexception $ e) {19 $ M-> rollback (); // roll back 20 die (" submission failed! "); 21}
PDO Transaction Processing