duanchan9354 2016-07-25 23:24
浏览 27
已采纳

在事务中间重定向是正常的事情吗?

Here is a transaction structure:

try {
    $dbh_con->beginTransaction();

    // queries here

    $dbh_con->commit();

} catch(PDOException $e) {

    $dbh_con->rollBack();

}

Now I want to know can I use header('Location: ../); in the transaction? So what happens?

Here is 3 cases:

try {
    $dbh_con->beginTransaction();

    header('Location: ../mypage.php1'); // (1)

    // queries here

    $dbh_con->commit();

    header('Location: ../mypage.php2'); // (2)

} catch(PDOException $e) {

    header('Location: ../mypage.php3'); // (3)

    $dbh_con->rollBack();

}

Ok using a redirect code in where of (1), (2) and (3) is standard? And what happens with the queries in that case?

Based on the tests, when I redirect a script before commit() (even after queries), none of those queries never work. I mean nothing changes.

  • 写回答

1条回答 默认 最新

  • duanniying2342 2016-07-25 23:28
    关注

    Redirection doesn't occur as soon as you use header(). The script continues to execute as normal. The header() will only take effect when the first piece of content is sent to the browser.

    If you've set the same header multiple times, only the latest will be sent to the browser (the earlier setting is overwritten).

    header('Location: /a.php');
    ... do some work
    header('Location: /b.php');
    ...
    //one of the lines below will cause redirection to /b.php
    echo "first piece of content!"; //<- send to the browser if buffering is off
    ob_flush();// <- send contents to browser if buffering is on
    

    Of course in your example, if there is an exception, the catch block header will take effect since it will be the last set Location header.

    Setting the same header multiple times in your script makes it harder to debug. Set it in one place, once you have enough info to know where to send the user:

    try {
        $dbh_con->beginTransaction();
        // queries here
        $dbh_con->commit();
        $uri = '/a.php';
    
    } catch(PDOException $e) {
        $uri = '/b.php';
        $dbh_con->rollBack();
    
    } finally {
        header("Location: $uri");
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探