zoukankan      html  css  js  c++  java
  • 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();
    }

    ?>
  • 相关阅读:
    计算机网络基础:TCP运输连接管理(三次握手 + 四次挥手)
    Zookeeper集群及配置
    Maven安装及配置
    SpringMVC拦截器+Spring自定义注解实现权限验证
    Spring之AOP配置
    设置Google浏览器不缓存JS
    数据加密之AES
    SpringMVC配置多个自定义拦截器
    利用Zookeeper实现分布式锁
    数据加密之RSA
  • 原文地址:https://www.cnblogs.com/sdfgdrg/p/9994509.html
Copyright © 2011-2022 走看看