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);
  • 相关阅读:
    学完这 4 个小技巧,让你的移动端交互体验更加优秀
    Angular 项目搭建
    需求分析--分析需求
    需求分析--收集需求
    黑苹果+win 双系统 单硬盘安装
    小程序反编译
    计算机硬件基础(软考-网络中级)
    intellij idea 使用教程
    idea安装步骤
    volatile能保证有序性
  • 原文地址:https://www.cnblogs.com/leigood/p/5032770.html
Copyright © 2011-2022 走看看