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){
//...
}
//...
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With