beginTransaction PDO用于类方法

时间:2013-11-08 04:01:27

标签: php mysql pdo

   <?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
    }

}

?>

我想在类方法中使用$pdo->beginTransaction();。如果我的更新失败并使用updateAction()方法,我如何使用roalback()?

1 个答案:

答案 0 :(得分:3)

Transactioned updateAction()示例:

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();
    }
}

请注意,如果要返回受影响的行数,则必须在提交后执行此操作。并且您希望在回滚后在false块上返回0或catch