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

前端 未结 3 1443
一生所求
一生所求 2021-01-23 08:02

I\'m pretty new to transactions.

Before, what I was doing was something like:

Code Block 1

$db = new PDO(...);

$stmt = $db->prepare(         


        
相关标签:
3条回答
  • 2021-01-23 08:40

    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;
    }
    
    0 讨论(0)
  • 2021-01-23 08:41

    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;
    }
    
    0 讨论(0)
  • 2021-01-23 09:04

    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;
    }
    
    0 讨论(0)
提交回复
热议问题