gpt4 book ai didi

php - PDO - 扩展类中的 beginTransaction()

转载 作者:行者123 更新时间:2023-11-29 10:03:02 24 4
gpt4 key购买 nike

我目前正在重构我的代码并收到以下错误:

Uncaught PDOException: There is no active transaction in...

 class Dbh {

private $serverName;
private $userName;
private $password;
private $dbName;

public function connect(){

$this->serverName = "localhost";
$this->userName = "root";
$this->password = "password";
$this->dbName = "rms";
$this->charset = "utf8";

$dsn = "mysql:host=" . $this->serverName . ";dbname=" . $this->dbName . ";charset=" . $this->charset;
$pdo = new PDO($dsn, $this->userName, $this->password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

return $pdo;
}

}


class General extends Dbh {

public function putHistory($consultantID, $type, $typeID) {

$this->connect()->beginTransaction();

$stmt = $this->connect()->prepare("INSERT INTO History (consultantID, type, typeID) VALUES (:consultantID, :type, :typeID) ");
$stmt -> execute(array(':consultantID' => $consultantID, ':type' => $type, ':typeID' => $typeID));

$this->connect()->commit();
}

}

$GeneralObject = new General;
$GeneralObject -> putHistory("1", "2", "3");

我想我在这种情况下错误地调用了 beginTransaction()/commit()

如何解决这个问题?

最佳答案

我认为错误是由于多次调用 $this->connect() 造成的,您在 putHistory() 中调用了 3 次。因此每次都会返回一个新的 $pdo 对象。我建议您仅调用 $this->connect() 一次并将其值存储在变量中,然后调用以下函数:beginTransaction()提交()

关于php - PDO - 扩展类中的 beginTransaction(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52512362/

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