Home>Article>Backend Development> php transaction processing method based on pdo

php transaction processing method based on pdo

墨辰丷
墨辰丷 Original
2018-05-19 10:40:12 1444browse

This article mainly introduces the transaction processing method based on pdo in PHP, and analyzes the related implementation techniques of PDO using pdo for transaction operations in the form of examples. Friends in need can refer to the

examples 1:

try {} catch () {} form

setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { die("数据库连接失败".$e->getMessage()); } //2.执行数据操作 try{ //开启事物,此时会关闭自动提交 $pdo->beginTransaction(); $sql = "insert into cy_log (logid, value, action, file) values (?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); //传入参数 $stmt->execute(array(null,"test4","w",11)); $stmt->execute(array(null,"test5","w",11)); $stmt->execute(array(null,"test3","w",11)); //提交事物,并且 数据库连接返回到自动提交模式 $pdo->commit(); }catch(PDOException $e){ echo '执行失败'.$e->getMessage(); //如果数据库被设置成自动提交模式,rollback 在回滚事务之后将恢复自动提交模式。 //包括 MySQL 在内的一些数据库, 当在一个事务内有类似删除或创建数据表等 DLL 语句时,会自动导致一个隐式地提交。 //隐式地提交将无法回滚此事务范围内的任何更改。即 DDL 语句无法回滚 $pdo->rollback(); }

Example 2:

if…else…form

getMessage()); } //2.执行数据操作 //开启事物 $pdo->beginTransaction(); $sql = "insert into cy_log (logid, value, action, file) values (?, ?, ?, ?)"; $stmt = $pdo->prepare($sql); $datalist = array( array(null,"test9","w",11), array(null,"test10","w",11), array(null,"test11","w",11) ); //是否提交标志位 $isCommit = true; foreach($datalist as $data){ $stmt->execute($data); if($stmt->errorCode()>0){ //回滚 $pdo->rollback(); $isCommit = false; break; } } if($isCommit){ //提交事物 $pdo->commit(); }

Related recommendations:

##PHP Understand the PDO database abstraction layer, phppdo database abstraction_PHP tutorial

##php uses PDO method in detail, phppdo in detail_PHP tutorial

PHP implements PDO's mysql database operation class, phppdomysql database_PHP tutorial

The above is the detailed content of php transaction processing method based on pdo. 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