A, PHP transaction processing Overview:
Transactions: A collection of several events
Transactions: When all events are executed successfully, the transaction is executed, and if any one of the events fails to execute successfully, the other events of the transaction are not executed.
As long as your MySQL version supports BDB or InnoDB table types, your MySQL has the ability to handle transactions. This is the most used InnoDB table type, although later, such as Oracle acquisition InnoDB and other things that make MySQL uncomfortable, but this kind of business events and technology, the following on the InnoDB table type as an example of a simple case of MySQL transaction processing.
Second, the 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);//Set exception handling mode
$pdo->setattribute (pdo::attr_autocommit,0);//Turn off autocommit
}catch (Pdoexception $e) {
echo "Database connection failed";
Exit
}
try{
$age = 10;
$pdo->begintransaction ()//Start 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 '");/change to make it succeed or fail
/* IF ($affected _rows1&& $affected _rows2)
{
$pdo->commit ();
echo "Successful operation";
}else{
$pdo->rollback ();
} */
if (! $affected _rows1)
throw new Pdoexception ("Add error");
if (! $affected _rows2)
throw new Pdoexception ("reduce error");
echo "Successful operation";
$pdo->commit ();//If the previous two update SQL statements were executed successfully, the entire transaction was successfully executed
}catch (Pdoexception $e) {
Echo "Operation failed:". $e->getmessage ();
$pdo->rollback ()//The statement in the execution transaction is out of question and the entire transaction is undone
}
$pdo->setattribute (pdo::attr_autocommit,1);
Whether the test was successful
echo "N operation result is: n";
$sql = "SELECT * from Kfry";
$result = $pdo->query ($sql);
foreach ($result as $v)
{
echo $v [' K_name ']. ". $v [' K_age ']." n ";
}
?>