PDO的事务处理

<?php
header('content-type:text/html;charset=utf-8');
include 'PdoClass.php';
$objPdo=new PdoClass();
//事务
try{
$dsn = "mysql:host=localhost;dbname=xxx";
$username = "root";
$password = 'root';
$pdo = new PDO($dsn, $username, $password,array(PDO::ATTR_AUTOCOMMIT=>0,PDO::ATTR_DEFAULT_FETCH_MODE=> PDO::FETCH_ASSOC,PDO::ATTR_CASE=>PDO::CASE_LOWER)) ;
$pdo->exec('set names utf8');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
echo "connect fail:".$e->getMessage();
exit;
}
try{
$pdo->beginTransaction();
$price = 500;
$list=$objPdo->getAll('user');
$goods = $objPdo->getAll('goods');
//print_r($goods);die;
$res=$list[0]['money'];
$goods_count=$goods[0]['g_count'];
if($res<500){
throw new PDOException('从A帐号中扣出失败');
}else if($goods_count==0){
throw new PDOException('从商品表中扣出失败');
}else {
$sql = "update user set money=money-{$price} where u_id=1";
$pdo->exec($sql);
$sql1 = "update user set money=money+{$price} where u_id=2";
$pdo->exec($sql1);
$sql2 = "update goods set g_count=g_count-1 where g_id=1";
$pdo->exec($sql2);
}
$pdo->commit();
} catch (PDOException $ex) {
$pdo->rollBack();
$title = isset($_POST['title'])?$_POST['title']:'';
$list = $objPdo->getAll('user',$title);
$goods = $objPdo->getAll('goods',$title);
include 'form.html';
echo $ex->getMessage();
}

?>

猜你喜欢

转载自www.cnblogs.com/sdfgdrg/p/9994509.html