Mysql transaction processing application instance of pdo in php. This article will introduce you to mysql transaction processing application instances of pdo in php. For more information, see. Php + mysql transaction processing steps: 1. disable automatic submission 2. start this article to introduce you to mysql transaction processing application instances of pdo in php. For more information, see.
Several steps for php + mysql transaction processing:
1. disable automatic submission
2. start transaction processing
3. if an exception exists, the system automatically throws the exception prompt and rolls back.
4. enable automatic submission
Note: Only the InnoDB driver in mysql supports transaction processing. by default, the MyIsAM driver does not.
The following is the instance code:
The code is as follows: |
|
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 |
Bytes. Php + mysql transaction processing steps: 1. disable automatic commit 2. enable...