$pdo -> beginTransaction(); //开启事务
$pdo -> rollBack(); //事务回滚
$pdo -> commit(); //事务提交
$pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1); //自动提交
实例
<?php
$dsn = 'mysql:host=localhost;dbname=mysqli';
$pdo = new PDO($dsn,'root','root');
$pdo -> exec('set names utf8');
$pdo -> beginTransaction();//开启事务
$sql1 = "UPDATE users SET money=money-10 WHERE id=1";
$r1 = $pdo -> exec($sql1);
$sql2 = "UPDATE users SET money=money+500 WHERE id=2";
$r2 = $pdo -> exec($sql2);
if ($r1>0 && $r2>0){
$pdo -> commit();
}else{
$pdo -> rollBack();
}
$pdo -> setAttribute(PDO::ATTR_AUTOCOMMIT,1);
发表评论