繁体   English   中英

如何正确使用MySQL事务

[英]How to use MySQL transactions properly

我需要协助。

我有不同的文件。 例如:

  • index.php,news.php
  • 包含脚本,例如:facebook.php,pay.php等。

在所有页面上(news.php除外),事务在脚本的开头开始,并在脚本的结尾处结束。

在index.php和news.php之类的页面上,我包含pay.php。 但是问题是:当我访问index.php时,一个事务已经开始,因此现在有两个事务处于活动状态! 但是我无法从pay.php中删除事务开始,因为如果我从news.php调用脚本,则不会有活动事务。

(我的网站复杂得多,包含更多页面和内容)。

有人能帮助我吗? 谢谢!

最好的选择是模拟嵌套事务。 为此,为您的数据库访问编写一个包装器。(pseduocode)

class MyMysqli {
    protected $realDb;
    protected $transaction_count =0;

    public function __construct ($host, $username , $passwd, $dbname){
        $this->realDb = new Mysqli($host, $username, $passwd, $dbname);
    }
    public function __get($property){
        return $this->realDb->$property;
    }

    public function __set($property, $value){
        return $this->realDb->$property = $value;
    }

    public function __call($method, $args){
        return call_user_func_array(array($this->realDb, $method), $args);
    }

    // overload begin_transaction, commit and rollback
    public function begin_transaction(){
         $this->transaction_count++;
         if ($this->transaction_count == 1){
               $this->realDb->begin_transaction();
         }
    }
    public function commit(){
         $this->transaction_count--;
         if($this->transaction_count == 0){
              $this->realDb->commit();
         }
    }

    public function rollback(){
         throw new Exception("Error");
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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