dongqindu8110 2016-07-15 21:39
浏览 22
已采纳

PDO交易api如何运作?

Here is my code structure:

// db connection here

try {
    $dbh_conn->beginTransaction();

    $stm = $dbh_conn->prepare("SELECT user_id FROM resend_pass WHERE token = ?");
    $stm->execute(array('value'));
    $num_rows = $stm->fetch(PDO::FETCH_ASSOC);

    if($num_rows) {
        echo 'one'; die;

    } else {
        echo 'two'; die;

    }

    $dbh_conn->commit();

} catch(PDOException $e) {
    $dbh_conn->rollBack();

    echo 'three'; die;

}

When exactly that query executes? You know, my script works exactly as expected. But I'm wonder how? As you see there is an if - else statement before commite(); Also both if and else have die; in their blocks. So as far as I know, this line never executes:

$dbh_conn->commit();

Because there is surly a die before it. But surprisingly my code works as well. Here is all possible outputs:

  • It prints one if value exists as a token in the resend_pass table.
  • It prints two if value doesn't exist as a token in the resend_pass table.
  • It prints three if there is an error (like syntax SQL error)

See? All fine. But how? When exactly commit() function executes? Before those dies ?

Note: The engine of resend_pass is innoDB.

  • 写回答

1条回答 默认 最新

  • dsnnvpobaljihv3490 2016-07-15 22:51
    关注

    Queries execute when execute() is called (note that query() calls execute()).

    If the query changes data in a table that supports transactions, the change is rolled back if the PDO object is freed, either because the object goes out of scope or the script terminates and cleans up. This is due to the PDO code, not MySQL.

    If the query changes data in a table that does not support transactions (e.g. a MyISAM table), the change is permanent at the time it is executed, and it cannot be rolled back.

    There are some SQL statements that perform an implicit commit. They would be made permanent as soon as they executed, even if your script dies before calling commit().

    As @MarcB mentioned, your example shows a read-only SELECT statement. It would be easier to test the behavior if you use an INSERT/UPDATE/DELETE.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答