PHP 处理 MySQL INNODB 事务回滚(ThinkPHP、MySQL、PDO)

参考文档    http://liuxufei.com/weblog/jishu/971.html


<?php
    $tranDb = new Model();

    // 启动事务
    $tranDb->startTrans();

    // 准备数据
    $sql = array('aaa' => 1);
    $res1 = $tranDb->table(C('DB_PREFIX').'user_count')->where('uid = 1')->save($sql);
    $res2 = $tranDb->table(C('DB_PREFIX').'hotel_order')->where('orderid = 1000')->save(array('status' => 1));

    if ($res1 && $res2) {
        // 提交事务
        $tranDb->commit(); 
        echo '<div style="color:blue;">成功</div>';
    }
    else {
        // 事务回滚
        $tranDb->rollback(); 
        echo '<div style="color:red;">失败</div>';
    }

2、MySQL 原生事务回滚

<?php
    $conn = mysql_connect('127.0.0.1', 'root', 'root');
    mysql_select_db('shop_test');
    mysql_query('SET NAMES UTF8');

    # 开启事务
    mysql_query("START TRANSACTION");
    
    $sql1 = "INSERT INTO `user_order` VALUES ('1', 'luchanghong', '10', '2')";
    $sql2 = "UPDATE `user_account` SET `money` = `money` - 10*2 WHERE `user` = 'luchanghong'";
    
    $res1 = mysql_query($sql1);
    $res2 = mysql_query($sql2);

    // if (mysql_errno()){
    if ($res1 && $res2){
        // 提交事务
        mysql_query('COMMIT');
        echo "成功";
    }else{
        // 事务回滚
        mysql_query('ROLLBACK');
        echo "失败";
    }

3、PDO 事务回滚

<?php
    try {
        $dsn = 'mysql:dbname=sunyang;host=localhost';
        $user_name = 'root';
        $user_psw = 'root';
        $pdo = new PDO($dsn, $user_name, $user_psw);
        
        //开始事务
        $pdo->beginTransaction();       
        $pdo->exec('update employee set emp_age=28 where emp_id=3');
        $pdo->exec('delete from employee where emp_id=2');
        
        //提交事务
        $pdo->commit();                 
    } catch (Exception $e) {
    
        //回滚事务
        $pdo->rollBack();               
        echo $e->getMessage();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值