如何正确使用MySQL事务 [英] How to use MySQL transactions properly

查看:160
本文介绍了如何正确使用MySQL事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助.

我有不同的文件.例如:

I have different files. For example:

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

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

On all the pages (except news.php) a transaction is started at the beginning of the script, and ending at the end of the script.

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

On pages like index.php and news.php, I include pay.php. But the problem is: when I'm visiting index.php a transaction is already started, so now two transactions are active! But I can't remove the transaction-start from pay.php, because if I call the script from news.php there is no active transaction.

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

(My website is much more complex with many more pages and things).

有人可以帮我吗?谢谢!

Can someone help me please? Thanks!

推荐答案

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

Your best bet is to emulate nested transactions. To do this write a wrapper for your database access.(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");
    }

这篇关于如何正确使用MySQL事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆