zoukankan      html  css  js  c++  java
  • 夺命雷公狗---PDO NO:7 事务处理

    示例:

    <?php
    header(“Content-Type:text/Html;Charset=utf-8″);
    try{
        //创建对象
        $pdo=new PDO(“mysql:host=localhost;dbname=xsphp”,’root’,”);
        //设置错误使用异常的模式
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        //关闭自动提交
        $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,0);
    }catch(PDOException $e){
        echo “数据库连接失败:”.$e->getMessage();
    exit;
    }
    try{
        //开启一个事务
        $pdo->beginTransaction();
        $price=50;
        //小红转出50元
        $affected_rows = $pdo->exec(“update ren set kee=kee-{$price} where id=1″);
        if($affected_rows>0){
            echo “小红转出{$price}元.<br/>”;
        }else{
            throw new PDOException(“小红转出失败<br/>”);
        }
    //李白会收到50元    因为在我表上没有id=3的所有会提示交易失败,失败而且钱不会减少
        $affected_rows=$pdo->exec(“update ren set kee=kee+{$price} where id= 3″);
        if($affected_rows){
            echo “李白收到{$price}元成功”;
        }else{
            throw new PDOException(“李白收入失败”);
        }
    echo ‘交易成功!<br/>';
        $pdo->commit();
            }catch(PDOException $e){
                echo “错误:”.$e->getMessage();
                echo “交易失败!<br/>”;
                $pdo->rollback();
        }
    $pdo->setAttribute(PDO::ATTR_AUTOCOMMIT,1);
  • 相关阅读:
    go通道小案例
    go执行cmd命令并获取输出内容
    vue快速生成二维码
    vue.js数字简化 万转化k显示
    uniapp实现小程序获取用户信息
    实现图片预加载功能
    C# MD5加密字符串方法
    一个封装的 HttpClientHelper
    简易通过队列存储并异步打日志实现
    变量
  • 原文地址:https://www.cnblogs.com/leigood/p/5032770.html
Copyright © 2011-2022 走看看