1
   <?php

class dbLayer
{

    //connection from here 

    private $done;

    function __construct(PDO $connection)
    {
        $this->done = $connection;

    }

    public function createAction()
    {
        //create a new  item
    }

    public function readAction()
    {
        //read all the  items
    }

    public function updateAction()
    {

        $sql = $this->done->prepare("UPDATE `sync_log` SET `Sync_Status`=? WHERE `randKey`=?");
        $sql->execute(array(
            $status,
            $randKey
        ));
    }

    public function deleteAction()
    {
        //delete a item
    }

}

?>

I want to use $pdo->beginTransaction(); with class methods.How i use roalback() if my update fail with updateAction() method ?

underscore
  • 6,495
  • 6
  • 39
  • 78

1 Answers1

3

Transactioned updateAction() example:

public function updateAction()
{
    try {
        $this->done->beginTransaction();
        $sql = $this->done->prepare("UPDATE `sync_log` SET `Sync_Status`=? WHERE `randKey`=?");
        $sql->execute(array(
            $status,
            $randKey
        ));
        $this->done->commit();
    } catch (PDOException $e) {
        $this->done->rollback();
    }
}

Note that if you want to return the affected rows count you must do that after commit. And you would like to return 0 or false on catch block after rollback.

Paulo Freitas
  • 13,194
  • 14
  • 74
  • 96
  • What about the exception? How are you meant to tell something went wrong? – Phil Nov 08 '13 at 05:11
  • There's no reason to downvote since it's outside the question... My follow-up comment (based on OP answer that was deleted) is assuming that OP wants to silently fail. If OP had asked that, I'd have rethrowed the exception after rollback. – Paulo Freitas Nov 08 '13 at 05:29