我目前正在重构代码并收到以下错误:
未捕获的PDOException:...中没有活动事务
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()
,commit()
。
关于php - PDO-扩展类中的beginTransaction(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52512362/