Home  >  Article  >  Backend Development  >  When does php use transactions?

When does php use transactions?

(*-*)浩
(*-*)浩Original
2019-10-26 11:39:083095browse

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:

<?php
	$link = mysqli_connect(&#39;localhost&#39;,&#39;username&#39;,&#39;password&#39;);					//创建链接

	if(!$link) exit(&#39;数据库连接失败&#39;);											//判断是否链接成功

	mysqli_set_charset($link , &#39;utf8&#39;);											//设置字符集
	
	mysqli_select_db($link,&#39;myDatabase&#39;);										//选择数据库

	$sql1 = "正确的插入语句";													//准备sql语句
	$sql2 = "错误的插入语句";													

	$result1 = mysqli_query($link , $sql1);										//发送sql语句
	$result2 = mysqli_query($link , $sql2);	

	if($result1 && $result2) {
		mysql_query(“COMMIT”);													//提交事务
		echo "提交成功";
	} else {
		mysql_query("ROLLBACK");
		echo &#39;数据回滚&#39;;
	}

	mysql_query("END");															//事务结束

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(&#39;shiwu2&#39;,&#39;shiwu2&#39;,&#39;456456456&#39;,&#39;456456456&#39;)");
     $pdo->exec("insert into t2(username,password,rtime,rip) values(&#39;shiwu2&#39;,shiwu2&#39;,&#39;456456456&#39;,&#39;456456456&#39;)");
     
     //提交事务
     $pdo->commit();
     //PDO   PDOStatement  PDOException
} catch(PDOException $e) {
	 //回滚事务
     $pdo->rollBack();
	 echo "数据回滚";    
}

Using transactions in TP5 framework

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

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!

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