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?