夺命雷公狗---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);
原文地址:https://www.cnblogs.com/leigood/p/5032770.html