Detailed Explanation of php Transaction Processing Example

  • 2021-07-07 06:42:21
  • OfStack

1. Overview of php transactions:

Transaction: A collection of events
Transaction processing: When all events are successfully executed, the transaction will be executed; If any 1 event cannot be successfully executed, other events of the transaction will not be executed.

As long as your version of MySQL supports BDB or InnoDB table types, your MySQL has transaction processing capabilities. Among them, InnoDB table type is used most. Although something unpleasant happened to MySQL, such as Oracle acquiring InnoDB, this kind of business event has nothing to do with technology. Let's take InnoDB table type as an example to briefly talk about the transaction processing in MySQL.

2. php transaction code:


<?php
 try{
 $pdo=new PDO("mysql:host=localhost;dbname=psp","root","");
 $pdo->exec("set names utf8");
 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);// Setting 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 a 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 at will to make it succeed or fail 
 /* if($affected_rows1&&$affected_rows2)
 {
  $pdo->commit();
  echo " Operation successful ";
 }else{
  $pdo->rollback();
 } */
 if(!$affected_rows1)
  throw new PDOException(" Join error ");
 if(!$affected_rows2)
  throw new PDOException(" Reduce errors ");
 echo " Operation successful ";
 $pdo->commit();// If you perform the first two updates here sql Statement executes successfully, and the whole transaction executes successfully 
 }catch(PDOException $e){
 echo " Operation failed: ".$e->getMessage();
 $pdo->rollback();// There is a problem in executing the statement in the transaction, and the whole transaction is undone 
 }
 $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,1);
 // Is the test successful 
 echo "\n The result of the operation is :\n";
 $sql="select * from kfry";
 $result=$pdo->query($sql);
 foreach($result as $v)
 {
 echo $v['k_name']." ".$v['k_age']."\n";
 }
?>

Related articles: