<?php
header('content-type:text/html;charset=utf-8');
try{
$dsn='mysql::host=localhost;dbname=test1';
$username='root';
$password='root';
$options=array(PDO::ATTR_AUTOCOMMIT,0);//关闭自动提交
$pdo=new PDO($dsn,$username,$password,$options);
//开启事务
$pdo->beginTransaction();
$sql="update useraccount set money=money-2000 where username='aa'";
$res=$pdo->exec($sql);
if($res==0) {
throw new PDOException('aa转账失败');
}
$sql1="update useraccount set money=money+2000 where username='bb'";
$res1=$pdo->exec($sql1);
if($res1==0){
throw new PDOException("bb接收失败");
}
//提交事务
$pdo->commit();
}catch (PDOException $e){
//回滚事务
$pdo->rollBack();
echo $e->getMessage();
}
?>
PDO事务实例
最新推荐文章于 2022-04-11 22:24:37 发布