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 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解
  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式