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('localhost','username','password'); //创建链接 if(!$link) exit('数据库连接失败'); //判断是否链接成功 mysqli_set_charset($link , 'utf8'); //设置字符集 mysqli_select_db($link,'myDatabase'); //选择数据库 $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 '数据回滚'; } mysql_query("END"); //事务结束
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('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 "数据回滚"; }
TP5 Framework:
//模型方法 function demo{ //开启事务 $this->startTrans(); //业务逻辑操作 $data['id'] = 1; $res = $this->insertUserInfo($data); //保存用户信息 if($res) { //提交事务 $this->commit(); return $res; } else { //事务回滚 $this->rollback(); } }
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!