gpt4 book ai didi

php - 如何正确使用MySQL事务

转载 作者:行者123 更新时间:2023-11-29 13:43:54 28 4
gpt4 key购买 nike

我需要一些帮助。

我有不同的文件。例如:

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

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

在像index.php和news.php这样的页面上,我包含了pay.php。但问题是:当我访问index.php时,一个事务已经启动,所以现在有两个事务处于事件状态!但我无法从 pay.php 中删除 transaction-start,因为如果我从 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");
}

关于php - 如何正确使用MySQL事务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17708401/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com