Should I do
$dbh->beginTransaction();
try{
Or
try{
$dbh->beginTransaction();
It doesn't really matter, it will run the code indifferent of it's position.
But you want to put the rollback()
in the catch
, and with that setup it's not readable if you put begin
outside.
I would vote for inside the try
.
It probably doesn't really matter. However, it's better to place the beginTransaction
outside the try
. When the beginTransaction
fails, it should not execute the rollback
.
add it inside the try
/catch
block, so you can catch any PDOException
:
try {
$dbh->beginTransaction(); // start transaction
$stmt = $dbh->query($query); // run your query
$dbh->commit(); // commit
} catch(PDOException $ex) { // if exception, catch it
$dbh->rollBack(); // rollback query
echo $ex->getMessage(); // echo exception message
}
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