PDO-扩展类中的beginTransaction()

时间:2018-09-26 07:35:34

标签: php mysql class pdo extend

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

  

未捕获的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()吗?

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

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