Home  >  Article  >  Backend Development  >  Detailed explanation of php transaction processing

Detailed explanation of php transaction processing

怪我咯
怪我咯Original
2017-07-12 16:29:034520browse

MySQL transactions are mainly used to process data with large operations and high complexity. For example, in the personnel management system, if you delete a person, you need to delete not only the basic information of the person, but also the information related to the person, such as mailbox, articles, etc. In this way, theseDatabase OperationThe statement constitutes a transaction!

1. Overview of PHP transaction processing:

Transaction: is a collection of several events
Transaction processing: The transaction will be executed only when all events are executed successfully; 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 that made MySQL unhappy, such as Oracle's acquisition of InnoDB, happened later, such business events have nothing to do with technology. Let's take the InnoDB table type as an example. Let’s briefly talk about transaction processing in MySQL.

2. PHP transaction processing 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);//设置异常处理模式
 $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,0);//关闭自动提交
 }catch(PDOException $e){
 echo "数据库连接失败";
 exit;
 }

 try{
 $age=10;
 $pdo->beginTransaction();//开始事务
 $affected_rows1=$pdo->exec("update kfry set k_age=k_age+{$age} where k_name=&#39;user1&#39;");
 $affected_rows2=$pdo->exec("update kfry set k_age=k_age-{$age} where k_name=&#39;user2&#39;");//随意更改使之执行成功或失败
 /* if($affected_rows1&&$affected_rows2)
 {
  $pdo->commit();
  echo "操作成功";
 }else{
  $pdo->rollback();
 } */
 if(!$affected_rows1)
  throw new PDOException("加入错误");
 if(!$affected_rows2)
  throw new PDOException("减少错误");
 echo "操作成功";
 $pdo->commit();//如果执行到此处前面两个更新sql语句执行成功,整个事务执行成功
 }catch(PDOException $e){
 echo "操作失败:".$e->getMessage();
 $pdo->rollback();//执行事务中的语句出了问题,整个事务全部撤销
 }
 $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,1);
 //测试是否成功
 echo "\n操作结果为:\n";
 $sql="select * from kfry";
 $result=$pdo->query($sql);
 foreach($result as $v)
 {
 echo $v[&#39;k_name&#39;]." ".$v[&#39;k_age&#39;]."\n";
 }
?>

The above is the detailed content of Detailed explanation of php transaction processing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn