dsdtszi0520538 2013-07-17 19:18 采纳率: 100%
浏览 103
已采纳

如何正确使用MySQL事务

I need some help.

I have different files. For example:

  • index.php, news.php
  • include-scripts like: facebook.php, pay.php and more.

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.

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!

  • 写回答

1条回答 默认 最新

  • douzhi9635 2013-07-17 19:53
    关注

    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");
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制