在执行rollBack()函数之前,PDO如何回滚查询? [英] How PDO rollbacks the queries before executing rollBack() function?

查看:106
本文介绍了在执行rollBack()函数之前,PDO如何回滚查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的剧本:

try {
    $dbh_con->beginTransaction();

        $stmt1 = $dbh_conn->prepare("UPDATE activate_account_num SET num = num + 1");
        $stmt1->execute();

        $stmt2 = $dbh_con->prepare("SELECT user_id FROM activate_account WHERE token = ?");
        $stmt2->execute(array($token));
        $num_rows = $stmt2->fetch(PDO::FETCH_ASSOC);

        if ( $num_rows['user_id'] ){
            $_SESSION['error'] = 'all fine';

        } else {
            $_SESSION['error'] = 'token is invalid';
            header('Location: /b.php');
             exit();
        }

    $dbh_con->commit();

    header('Location: /b.php');
    exit();

} catch(PDOException $e) {

    $dbh_con->rollBack();

    $_SESSION['error'] = 'something is wrong';
    header('Location: /b.php');
    exit();
}

如您所见,该else块包含exit()函数.因此,当执行该else块时,肯定会不执行该rollBack();函数,因为在执行rollBack();之前,该脚本将退出.但是令人惊讶的是,UPDATE语句回滚了.

As you see, that else block contains exit() function. So when that else block executes, then surely that rollBack(); function doesn't execute, because before executing rollBack();, the script exits. But surprisingly that UPDATE statement rollbacks.. How ?

推荐答案

在所有更改都一起发生或根本不发生更改的关键条件下使用事务.

Transactions are used when it's critical that all changes happen together, or no change happens at all.

为了在突然停止(例如,脚本意外退出,服务器崩溃,电源中断...)的情况下保持数据库的完整性,事务的实现将保护您,直到commit()被调用.当您execute中间查询时,更改实际上并没有影响数据库,而是处于不确定状态.如果您不提交而退出,则边缘状态将被丢弃.

To preserve the integrity of the DB in the event of an abrupt stoppage (eg: script exits unexpectedly, server crashes, power supply is cut...), implementations of transactions will keep you protected by not making any change until commit() is called. When you execute intermediary queries, the change is not actually hitting the database, but held in limbo. If you exit without committing, the limbo is just thrown away.

当您rollBack()时,也只会丢掉边缘.

When you rollBack(), the limbo is also just thrown away.

这篇关于在执行rollBack()函数之前,PDO如何回滚查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆