Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO Will transaction rollback when execute fails?

Example code:

$pdo->beginTransaction();

try {   
    $query1 = $pdo->prepare(...);
    $query2 = $pdo->prepare(...);

    $query1->execute();
    $query2->execute();

    $pdo->commit();
} catch(Exception $e){
    try {
        $pdo->rollBack();
    } catch(Exception $re){
        //...
    }

    //...
}

I know that prepare can throw exception, and commit will throw exception if there is no transaction running.

But is it possible to occur such situation in which prepare will success but execute fails? It would not cause rollback? Does commit also throws when execution failed (I don't think so, as documentation says it throws only when there is no transaction).

So should I explicitly check for execution result and throw my own exceptions to cause rollback like this?:

$pdo->beginTransaction();

try {

    $query1 = $pdo->prepare(...);
    $query2 = $pdo->prepare(...);

    if(!$query1->execute()){
        throw new Exception('Query1 failed to execute.');
    }

    if(!$query2->execute()){
        throw new Exception('Query2 failed to execute.');
    }

    $pdo->commit();
} catch(Exception $e){
    try {
        $pdo->rollBack();
    } catch(Exception $re){
        //...
    }

    //...
}
like image 239
Mr_KoKa Avatar asked May 12 '26 08:05

Mr_KoKa


1 Answers

I assume that basically you're asking, does execute() throw an exception, if it fails?

Yes, it does.

Therefore your code will be rolled back automatically. No need for checking manually. You can test it with a duplicate unique key error for example.

like image 170
Your Common Sense Avatar answered May 14 '26 20:05

Your Common Sense



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!