dongpo9071 2016-05-20 08:13
浏览 268
已采纳

PHP,MySQL,PDO事务 - try块中的代码是否在commit()处停止?

I'm pretty new to transactions.

Before, what I was doing was something like:

Code Block 1

$db = new PDO(...);

$stmt = $db->prepare(...);

if($stmt->execute()){
    // success
    return true;
}else{
    // failed
    return false;
}

But in an attempt to group multiple queries into a single transaction, I'm now using something like:

Code Block 2

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$db->beginTransaction();

try{
    $stmt = $db->prepare(... 1 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 2 ...);
    $stmt->execute();

    $stmt = $db->prepare(... 3 ...);
    $stmt->execute();

    $db->commit();

    return true;
}catch(Exception $e){
    // Failed, maybe write the error to a txt file or something
    $db->rollBack();
    return false;
}

My question is: If the transaction fails for whatever reason, does the code stop at $db->commit(); and jump to the catch block? Or would the return true; run first, and then it would try to go to the catch? 'Cause if that's the case, then I've already returned, and so it wouldn't go to the catch. AND it would have returned the wrong value.

Do I still need to include something like:

Code Block 3

if($stmt->commit()){
    return true;
}

or is it sufficient the way I have it written in Code Block 2?

  • 写回答

3条回答 默认 最新

  • dpafea04148 2016-05-20 08:44
    关注

    If the transaction fails for whatever reason, the code does stop at the very line where error occurred end then the execution jumps directly to the catch block. So it is sufficient the way you have it written in Code Block 2.

    Note that you should always re-throw the Exception after rollback. Otherwise you will never have an idea what was a problem. So it should be

    try{
        $stmt = $db->prepare(... 1 ...);
        $stmt->execute();
    
        $stmt = $db->prepare(... 2 ...);
        $stmt->execute();
    
        $stmt = $db->prepare(... 3 ...);
        $stmt->execute();
    
        $db->commit();
    
        return true;
    }catch(Exception $e){
        $db->rollBack();
        throw $e;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站