Home > Backend Development > PHP Problem > When to use php transactions

When to use php transactions

王林
Release: 2023-02-24 14:20:01
Original
3532 people have browsed it

When to use php 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 no longer be executed. Success will only be considered if all executions are successful, otherwise it will return to the state before execution, which requires transaction processing.

Native:

<?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");															//事务结束	
Copy after login

PDO:

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 "数据回滚";    
}
Copy after login

TP5 Framework:

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

The above content is for reference only!

Recommended tutorial: PHP video tutorial

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

Related labels:
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