Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you put the beginTransaction(); before or within the `try` block

Should I do

$dbh->beginTransaction();
try{

Or

try{
  $dbh->beginTransaction();
like image 868
JDelage Avatar asked Sep 16 '12 00:09

JDelage


3 Answers

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.

like image 117
Krycke Avatar answered Oct 31 '22 10:10

Krycke


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.

like image 3
Lode Avatar answered Oct 31 '22 10:10

Lode


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
}
like image 1
Mihai Iorga Avatar answered Oct 31 '22 11:10

Mihai Iorga