【问题标题】:PDO - beginTransaction() in extended classPDO - 扩展类中的 beginTransaction()
【发布时间】:2019-03-01 21:57:34
【问题描述】:

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

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()

我该如何解决这个问题?

【问题讨论】:

  • 通常会有一条错误消息指向代码中的特定行。这次是吗?
  • 每个connect() 都会建立一个新连接,因此一个人不知道另一个人的beginTransaction()
  • 抱歉,是的,它专门引用了 Uncaught PDOException: There is no active transaction in ...: PDO->commit()

标签: php mysql class pdo extend


【解决方案1】:

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

【讨论】:

  • 谢谢rock start - 我现在明白了... $connection = $this->connect();然后引用 $connection
猜你喜欢
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 2011-07-07
  • 2014-05-23
  • 2011-03-26
  • 2021-07-04
  • 2016-11-09
  • 2016-01-03
相关资源
最近更新 更多