PHP, MySQL, PDO Transactions - Does the code inside try block stop at commit()?

你离开我真会死。 提交于 2019-12-20 05:12:08

问题


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?


回答1:


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:


The execution is stopped when an exception is thrown.

The first return will not be reached but the catch statement will be executed.

You can even return the commit directly:

$dbh->beginTransaction();
try {
    // insert/update query
    return $dbh->commit();
} catch (PDOException $e) {
     $dbh->rollBack();
     return false;
}



回答3:


if you face any error you can do this to rollback all transactions like this

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


来源:https://stackoverflow.com/questions/37341399/php-mysql-pdo-transactions-does-the-code-inside-try-block-stop-at-commit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!