1. Overview of php transaction processing:
Transaction: It is a collection of several events
Transaction processing: When all events are executed successfully, the transaction is executed; if any event cannot be executed successfully, other events of the transaction will not be executed.
As long as your MySQL version supports BDB or InnoDB table types, then your MySQL has transaction processing capabilities. Among them, the InnoDB table type is the most used. Although things such as Oracle's acquisition of InnoDB later happened that made MySQL unhappy, such business events have nothing to do with technology. Let's take the InnoDB table type as an example to briefly talk about MySQL. transaction processing.
2. 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 automatic submission
}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 it at will to make the execution successful or failed
/* 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 update sql statements are executed successfully at this point, the entire transaction is executed successfully
}catch(PDOException $e){
echo "Operation failed:".$e->getMessage();
$pdo->rollback();//There is a problem with the statement in the execution transaction, and the entire transaction is canceled
}
$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";
}
?>