简体   繁体   中英

Transactions using PDO

My understanding is the InnoDB is now the default engine for MySQL. With that knowledge, I am beginning to delve into transactions.

Here is what I have so far...

try{
     $pdo->beginTransaction();
        $stmnt = $pdo->prepare ("delete from playing where uniq = :uniq");
        $stmnt->bindParam (':uniq',$uniq);
        $stmnt->execute();

        $stmnt = $pdo->prepare ("insert into removals (playdate, time, vid) values (:playdate, :time, :vid");
        $stmnt->bindParam (":playdate",$playdate);
        $stmnt->bindParam (":time", $time);
        $stmnt->bindParam (":vid", $vid);
        $stmnt->execute();

     $pdo->commit();

     echo "1"; // success
     return;
   }
   catch (PDOException $e){
      $pdo->rollback();
      echo $e->getMessage();
   }

This is called by jQuery with a result of "1" indicating a success.

If I understand this correctly, if bot statements execute successfully, they will both be "committed" however it either fails, no database activity will take place and an error message will be generated detailing the first statement execution that fails.

My real question is whether the begin transaction and commit should reside within or outside the try...catch block.

Thanks, -dmd-

For readability and cleanliness, yes it should be inside the try block. But it really does not matter. It just declares what to commit or rollback if you call roll back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM