Search code examples
phpmysqlclasspdoextend

PDO - beginTransaction() in extended class


I am currently refactoring my code and receiving the following error:

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");

I guess I'm calling the beginTransaction()/commit() incorrectly in this instance?

How can I solve this problem?


Solution

  • I think the error is due to calling $this->connect() multiple times, you are calling it 3 times in putHistory(). Hence every time a new $pdo object is returned. I'd recommend that you call $this->connect() only once and store its value in a variable and then call these functions: beginTransaction(), commit().