【问题标题】:How to use MySQL transactions properly如何正确使用 MySQL 事务
【发布时间】:2013-07-17 19:18:34
【问题描述】:

我需要一些帮助。

我有不同的文件。例如:

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

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

在 index.php 和 news.php 等页面上,我包含 pay.php。但问题是:当我访问 index.php 时,一个事务已经开始,所以现在有两个事务处于活动状态!但我无法从 pay.php 中删除 transaction-start,因为如果我从 news.php 调用脚本,则没有活动交易。

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

有人可以帮帮我吗?谢谢!

【问题讨论】:

  • 您需要更清楚地解释一下。这是什么交易?
  • 这是一个 MySQL 事务。喜欢stackoverflow.com/questions/2708237/…
  • @jordy well stop :) ...您真的应该采用较新的数据库引擎之一... mysql 扩展已被弃用。

标签: php mysql optimization transactions


【解决方案1】:

最好的办法是模拟嵌套事务。为此,请为您的数据库访问编写一个包装器。(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");
    }

【讨论】:

  • 谢谢,我不太擅长OOP,但是如何开始事务呢?我可以用这个做 MySQL 吗? (在进一步的阶段,我将整个网站更新为 MySQLi / PDO)
  • 现在是升级的好时机。但这个概念是只在第一次启动事务并增加一个变量,在提交时减少变量,如果它是 0 然后提交。
  • 用于您的谷歌搜索“在 mysql 中模拟嵌套事务”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2013-01-19
  • 1970-01-01
  • 2013-07-20
  • 2017-07-17
  • 2012-04-26
  • 2016-03-17
相关资源
最近更新 更多