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 "数据回滚"; }
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(); } }
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!