This article illustrates the usage of MySQL transaction processing under PHP PDO. Share to everyone for your reference. The specific analysis is as follows:
Several steps for PHP+MYSQL transaction processing:
1. Turn off automatic submission 2. Open transaction 3. Automatically throws an exception prompt and rolls back 4. Turn on autocommit
Note: MySQL has only this innodb driver that supports transaction processing, the default MyISAM driver is not supported, and the following is the instance code:
Copy Code code as follows:
<?php
try{
$pdo =new PDO ("Mysql:host=localhost;dbname=mydb", "root", "root", Array (pdo::attr_autocommit=>0));/finally turn off autocommit
$pdo->setattribute (pdo::attr_autocommit, 0);//This is done by setting the property method to turn off autocommit and the function above
$pdo->setattribute (Pdo::attr_errmode, pdo::errmode_exception);/Open Exception handling
}catch (Pdoexception $e) {
echo "Database connection failed:". $e->getmessage ();
Exit
}
/*
* Transaction Processing
*
* John bought a 2000-dollar computer from Dick.
* 2000 Yuan deducted from the John account
* Add 2000 RMB to Li's four account number
* Reduce a computer from the commodity list
* MyIsAM InnoDB
*/
try{
$pdo->begintransaction ()//Open transaction
$price = 500;
$sql = "Update Zhanghao set price=price-{$price} where id=1";
$affected _rows= $pdo->exec ($sql);
if (! $affected _rows)
throw new Pdoexception ("Zhang San turn out failed");//That 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 ("to Dick into failure");
echo "Transaction success! ";
$pdo->commit ()//The transaction was successfully submitted
}catch (Pdoexception $e) {
echo $e->getmessage ();
$pdo->rollback ();
}
$pdo->setattribute (Pdo::attr_autocommit, 1);//automatic submission, if the final does not automatically submit, the transfer is unsuccessful
Set Error Reporting mode Errmode_silent errmode_warning
?>
I hope this article will help you with your PHP program design.