Php transaction processing instance details
I. php transaction processing Overview:
Transaction: a collection of several events
Transaction Processing: When all events are successfully executed, the transaction is executed. If any event cannot be successfully executed, other events of the transaction will not be executed.
As long as your MySQL version supports the BDB or InnoDB table type, your MySQL has the ability to process transactions. In this regard, InnoDB tables are the most used. Although there were some unpleasant things such as Oracle's purchase of InnoDB, such commercial events were not related to technology, the following takes the InnoDB table type as an example to briefly describe the transaction processing in MySQL.
Ii. php transaction processing code:
Try {
$ Pdo = new PDO ("mysql: host = localhost; dbname = psp", "root ","");
$ Pdo-> exec ("set names utf8 ");
$ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); // sets the exception handling mode.
$ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 0); // disable automatic submission
} Catch (PDOException $ e ){
Echo "database connection failed ";
Exit;
}
Try {
$ Age = 10;
$ Pdo-> beginTransaction (); // start the transaction
$ Affected_rows1 = $ pdo-> exec ("update kfry set k_age = k_age + {$ age} where k_name = 'user1 '");
$ Affected_rows2 = $ pdo-> exec ("update kfry set k_age = k_age-{$ age} where k_name = 'user2'"); // modify it to make it successful or failed at will
/* If ($ affected_rows1 & $ affected_rows2)
{
$ Pdo-> commit ();
Echo "operation successful ";
} Else {
$ Pdo-> rollback ();
}*/
If (! $ Affected_rows1)
Throw new PDOException ("add error ");
If (! $ Affected_rows2)
Throw new PDOException ("reduce errors ");
Echo "operation successful ";
$ Pdo-> commit (); // if the first two updated SQL statements are successfully executed, the entire transaction is successfully executed.
} Catch (PDOException $ e ){
Echo "operation failed:". $ e-> getMessage ();
$ Pdo-> rollback (); // An error occurred while executing the statement in the transaction. The entire transaction is canceled.
}
$ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 1 );
// Test whether the task is successful
Echo "\ n operation result: \ n ";
$ SQL = "select * from kfry ";
$ Result = $ pdo-> query ($ SQL );
Foreach ($ result as $ v)
{
Echo $ v ['k _ name']. ". $ v ['k _ age']." \ n ";
}
?>