When does php use transactions?

(*-*)浩
Release: 2023-02-27 18:56:02
Original
2983 people have browsed it

When does php use transactions?

Some programs need to perform multiple actions when executing, and our business requirement is that when an action is executed incorrectly, all actions of the process will not When executing again, it will be considered successful only if all executions are successful. Otherwise, it will return to the state before execution, which requires transaction processing. (Recommended learning: PHP video tutorial)

The native code is as follows:

Copy after login

PDO code is as follows:

try {

	 //实例化PDO对象
	 $pdo = new PDO("mysql:host=localhost;dbname=test","root","root",array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));
   	 $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
	
	 //开启事务
	 $pdo->beginTransaction();
	  
	 //执行sql语句
	 $pdo->exec("insert into t1(username,password,rtime,rip) values('shiwu2','shiwu2','456456456','456456456')");
     $pdo->exec("insert into t2(username,password,rtime,rip) values('shiwu2',shiwu2','456456456','456456456')");
     
     //提交事务
     $pdo->commit();
     //PDO   PDOStatement  PDOException
} catch(PDOException $e) {
	 //回滚事务
     $pdo->rollBack();
	 echo "数据回滚";    
}
Copy after login

Using transactions in TP5 framework

//模型方法
function demo{
	//开启事务
	$this->startTrans();
	
	//业务逻辑操作
	$data['id'] = 1;
	$res = $this->insertUserInfo($data);		//保存用户信息
	
	if($res) {
		//提交事务
		$this->commit();
		return $res;
	} else {
		//事务回滚
		$this->rollback();
	}
}
Copy after login

The above is the detailed content of When does php use transactions?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!