pdo + 事务处理 处理线性事务

时间:2023-03-09 10:02:23
pdo + 事务处理  处理线性事务
/*
* 事物处理线性操作。
* 以转账为例
*/
header('Content-type:text/html;charset=utf-8'); $opt = array(PDO::ATTR_PERSISTENT => TRUE);
$dsn = "mysql:dbname=0328;host=127.0.0.1";
$user = "root";
$password = ''; $dbh = new PDO($dsn,$user,$password,$opt);
$dbh->setAttribute(PDO::ATTR_AUTOCOMMIT,0); //关闭自动提交
try{
$dbh->beginTransaction();
$price = 10;
$is_acheived = $dbh->exec("update account set money=money-$price where name='王贺军'");
if($is_acheived > 0){
echo '王贺军成功转出 ' . $price . '元<br>';
}else{
throw new PDOException("转出失败!<br>");
}
$is_acheived = $dbh->exec("update account set money=money+$price where name='王二'");
if($is_acheived > 0){
echo '王二成功转入 ' . $price . '元<br>';
}else{
throw new PDOException("转入失败!<br>");
}
echo '交易成功!';
$dbh->commit();
}catch(PDOException $e){
echo "交易失败 " . $e->getMessage();
$dbh->rollback();
}
$dbh->setAttribute(PDO::ATTR_AUTOCOMMIT,1); //开启自动提交