<?php
header('contentType:text/html;charset:utf8');
$dsn='mysql:host=localhost;dbname=imooc'; //事务操作,数据库存储引擎必须是InnoDB
$username='root';
$password='playboy';
try{
$options=array(PDO::ATTR_AUTOCOMMIT,0);
$pdo=new PDO($dsn,$username,$password,$options);
$pdo->beginTransaction();
$sql1='update userAccount set money=money-2000 where username="lbp"';
$res1=$pdo->exec($sql1);
if($res1==0){
throw new PDOException('LBP转账失败,未减少2000');
}
$sql2='update userAccount set money=money+2000 where username="xinian"';
$res2=$pdo->exec($sql2);
if($res2==0){
throw new PDOException('xinian转账失败,未增加2000');
}
$pdo->commit();
//echo '<script>alert ("successfully ");</script>';
echo '<h2 style="text-align:center;color:red;">交易成功</h2>';
}catch(PDOException $e){
echo $e->getMessage();
$pdo->rollBack();
}
?>
注意:数据库存储引擎必须是InnoDB