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.

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

报告相同问题?

悬赏问题

  • ¥50 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?