如何在PDO类中添加MySQL事务?

时间:2013-08-01 21:16:00

标签: php mysql pdo rollback autocommit

我有一个PDO类,我创建了帮助我连接并与MySQL服务器通信。 我想要做的是在类中添加一个函数或方法,它将帮助我向MySQL打开一个事务以及提交和回滚。我从未使用过提交和回滚。

我认为会使某个场景以某种方式在每次调用此类时停止自动提交,并在每次抛出错误时回滚并在每次关闭此类ID时提交。

我的2个问题是: 1)如果没有错误,打开连接然后运行多个查询是否是一个好主意,否则回滚然后关闭连接? 2)我如何设法将这个添加到我现有的课程中? 这是我目前的PHP类

<?php

class connection {

    private $connString;
    private $userName;
    private $passCode;
    private $server;
    private $pdo;
    private $errorMessage;
    private $pdo_opt = array();
    protected $lastQueryTime;
    protected $lastQuery;
    protected $effectedRows;



    function __construct($dbName = DATABASE_NAME, $serverName = DATABASE_HOST){

        //SET PDO options
        if(TESTING_ENVIRONMENT == 1){
            $this->pdo_opt[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
            $this->pdo_opt[PDO::ATTR_DEFAULT_FETCH_MODE]  = PDO::FETCH_ASSOC;
        }

            $this->pdo_opt[PDO::MYSQL_ATTR_INIT_COMMAND] = 'SET NAMES utf8';
            $this->pdo_opt[PDO::SQLSRV_ATTR_ENCODING]  = PDO::SQLSRV_ENCODING_UTF8;

        //sets credentials
        $this->setConnectionCredentials($dbName, $serverName);

        //start the connect
        $this->startConnection();

    }

    function startConnection(){


            $this->pdo = new PDO($this->connString, $this->userName, $this->passCode, $this->pdo_opt);

            if( ! $this->pdo){

                $this->errorMessage  = 'Failed to connect to database. Please try to refresh this page in 1 minute. ';
                $this->errorMessage .= 'However, if you continue to see this message please contact your system administrator.';
                echo $this->getError();
            }
    }


    //this will close the PDO connection
    public function endConnection(){

        $this->pdo = null;
    }

    //return a dataset with the results
    public function getDataSet($query, $data = NULL)
    {
        $start = microtime(true);
        $cmd = $this->pdo->prepare( $query );

        $cmd->execute($data);
        $this->effectedRows = $cmd->rowCount();
        $ret = $cmd->fetchAll();
        //$cmd->closeCursor();
        $this->lastQueryTime = microtime(true) - $start;
        $this->lastQuery = $query;

        return $ret;
    }



    public function processQuery($query, $data = NULL)
    {
        $start = microtime(true);
               //$this->pdo->beginTransaction();


        $cmd = $this->pdo->prepare( $query );
        $ret = $cmd->execute($data);
               //$this->pdo->commit();
               //$cmd->closeCursor();
        $this->effectedRows = $cmd->rowCount();
        $this->lastQueryTime = microtime(true) - $start;
        $this->lastQuery = $query;

        return $ret;
    }


    //return last insert id
    public function lastInsertId($name = NULL) {
        if(!$this->pdo) {
            return false;
        }

        return $this->pdo->lastInsertId($name);
    }


    //return last insert id
    public function rowCount() {

        return $this->effectedRows;
    }


    public function getOneResult($query, $data = NULL){
        $cmd = $this->pdo->prepare( $query );
        $cmd->execute($data);

        return $cmd->fetchColumn();
    }

    public function getError(){
        if($this->errorMessage != '')
            return $this->errorMessage;
        else
            return true;  //no errors found

    }

    //this where you need to set new server credentials with a new case statment
    function setConnectionCredentials($dbName, $serv){

        switch($serv){

            //the defaults are predefined in the APP_configuration file - DO NOT CHANGE THE DEFAULT
            default:
                $this->connString   = 'mysql:host='.DATABASE_HOST.';dbname='.DATABASE_NAME.';charset=utf8';
                $this->userName     = DATABASE_USERNAME;
                $this->passCode     = DATABASE_PASSWORD;
            break;

            }

    }

public function lastQueryTime() {
    if(!$this->lastQueryTime) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQueryTime;
}

public function lastQuery() {
    if(!$this->lastQuery) {
        throw new Exception('no query has been executed yet');
    }
    return $this->lastQuery;
}

}

?>

EDITED 收集通知后这是我需要的方式吗?

$db = new connection();
$db->beginTransaction(); //begin transaction
$db->processQuery();     //process query #1
$db->processQuery();     //process query #2
$db->commit();           //commit changes
$db->endConnection();    //close connection


public function beginTransaction(){
    $this->pdo->beginTransaction(); 
}

public function commit(){
    $this->pdo->commit(); 
}

public function rollBack(){
    $this->pdo->rollBack(); 
}   

//this will close the PDO connection
public function endConnection(){
    $this->pdo = null;
}

1 个答案:

答案 0 :(得分:0)

PDO::beginTransaction

/* Begin a transaction, turning off autocommit */
$dbh->beginTransaction();

PDO::commit

/* Commit the changes */
$dbh->commit();

此时,感觉您的connection课程水平相当低。我的猜测是,在开始事务和何时提交时,它没有足够的信息来自行了解。您可能必须提供相应的方法(以及rollback方法),并让您的类用户在需要时调用它们。


关于您的问题,交易不仅仅是回滚本地更改。它也是atomicity。这是全部完成完全没有完成的操作序列。不要忘记将同时访问您的数据库。有时您不希望有人在操作数据时更改数据。