Example of pdo-based transaction processing method implemented by php, pdo Transaction Processing
This example describes how to implement pdo-based transaction processing in php. We will share this with you for your reference. The details are as follows:
Instance 1:
Try {} catch () {} form
<? Php $ dsn = 'mysql: dbname = cheyun_cms; host = 127.0.0.1 '; $ user = 'root'; $ password = '2016 '; // use preprocessing + transaction processing to execute SQL operations // 1. connect to the database try {$ pdo = new PDO ($ dsn, $ user, $ password); $ pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION );} catch (PDOException $ e) {die ("database connection failed ". $ e-> getMessage ();} // 2. execute the data operation try {// enable the transaction. The automatic submission of $ pdo-> beginTransaction (); $ SQL = "insert into cy_log (logid, value, action, file) valu is disabled. Es (?, ?, ?, ?) "; $ Stmt = $ pdo-> prepare ($ SQL); // input parameter $ stmt-> execute (array (null," test4 "," w ", 11); $ stmt-> execute (array (null, "test5", "w", 11); $ stmt-> execute (array (null, "test3 ", "w", 11); // submit the transaction, and the database connection is returned to the automatic submission mode $ pdo-> commit ();} catch (PDOException $ e) {echo 'execution failed '. $ e-> getMessage (); // if the database is set to the automatic commit mode, rollback restores the automatic commit mode after the transaction is rolled back. // Some databases, including MySQL, are automatically committed implicitly when a transaction contains DLL statements such as deleting or creating a data table. // Implicitly commit will not be able to roll back any changes within this transaction range. That is, DDL statements cannot roll back $ pdo-> rollback ();}
Instance 2:
If... Else... Form
<? Php $ dsn = 'mysql: dbname = cheyun_cms; host = 127.0.0.1 '; $ user = 'root'; $ password = '2016 '; // use preprocessing + transaction processing to execute SQL operations // 1. connect to the database try {$ pdo = new PDO ($ dsn, $ user, $ password);} catch (PDOException $ e) {die ("database connection failed ". $ e-> getMessage ();} // 2. execute Data Operations // enable transactions $ pdo-> beginTransaction (); $ SQL = "insert into cy_log (logid, value, action, file) values (?, ?, ?, ?) "; $ Stmt = $ pdo-> prepare ($ SQL); $ datalist = array (null," test9 "," w ", 11), array (null, "test10", "w", 11), array (null, "test11", "w", 11); // whether to submit the flag bit $ isCommit = true; foreach ($ datalist as $ data) {$ stmt-> execute ($ data); if ($ stmt-> errorCode ()> 0) {// rollback $ pdo-> rollback (); $ isCommit = false; break;} if ($ isCommit) {// submit transaction $ pdo-> commit ();}
Note:
InnoDB type is required for data tables