PDO - 扩展中的 beginTransaction() class
PDO - beginTransaction() in extended class
我目前正在重构我的代码并收到以下错误:
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()
、commit()
.
我目前正在重构我的代码并收到以下错误:
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()
、commit()
.