This article mainly introduces the mysql transaction processing usage of pdo in php, and analyzes the usage of pdo-based transaction commit and rollback operations in the form of instances, which has some reference value, for more information, see
This article mainly introduces the mysql transaction processing usage of pdo in php, and analyzes the usage of pdo-based transaction commit and rollback operations in the form of instances, which has some reference value, for more information, see
This article describes the usage of mysql transaction processing for pdo in php. Share it with you for your reference. The specific analysis is as follows:
Several steps for php + mysql transaction processing:
1. Disable Automatic commit. 2. Enable transaction processing. 3. If an exception exists, an exception is automatically thrown, prompting you to roll back. 4. Enable Automatic commit.
Note: Only the InnoDB driver in mysql supports transaction processing. The MyIsAM driver does not support transaction processing by default. The following is the instance code:
The Code is as follows:
<? Php
Try {
$ Pdo = new pdo ("mysql: host = localhost; dbname = mydb", "root", "root", array (PDO: ATTR_AUTOCOMMIT => 0 )); // disable automatic submission.
// $ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 0); // This is to disable automatic submission by setting the attribute method, which is the same as the above function
$ Pdo-> setAttribute (PDO: ATTR_ERRMODE, PDO: ERRMODE_EXCEPTION); // enable Exception Handling
} Catch (PDOException $ e ){
Echo "Database Connection Failed:". $ e-> getMessage ();
Exit;
}
/*
* Transaction Processing
*
* John bought a 2000 yuan computer from Li Si.
* Deduct RMB 2000 from Michael Jacob's account
* Add RMB 2000 to the account Li Si
* Reduce a computer from the commodity table
* MyIsAM InnoDB
*/
Try {
$ Pdo-> beginTransaction (); // start Transaction Processing
$ Price = 500;
$ SQL = "update zhanghao set price = price-{$ price} where id = 1 ";
$ Affected_rows = $ pdo-> exec ($ SQL );
If (! $ Affected_rows)
Throw new PDOException ("Michael Jacob transfer failed"); // The error throws an exception.
$ SQL = "update zhanghao set price = price + {$ price} where id = 3 ";
$ Affected_rows = $ pdo-> exec ($ SQL );
If (! $ Affected_rows)
Throw new PDOException ("failed to transfer to Li Si ");
Echo "transaction successful! ";
$ Pdo-> commit (); // submit if the transaction is successful
} Catch (PDOException $ e ){
Echo $ e-> getMessage ();
$ Pdo-> rollback ();
}
$ Pdo-> setAttribute (PDO: ATTR_AUTOCOMMIT, 1); // automatic submission. If not, the transfer is unsuccessful.
// Set the error report mode ERRMODE_SILENT ERRMODE_WARNING
?>
I hope this article will help you with php programming.