0

I've created a class which wraps PDO:

<?php

class NewDatabase
{
  private static function connect(): PDO
  {
    try
    {
      $config = parse_ini_file(".env");
      $dsn = "mysql:host=".$config["NEW_DB_HOST"].";dbname=".$config["NEW_DB_NAME"];
      $pdo = new PDO($dsn, $config["NEW_DB_USER"], $config["NEW_DB_PASS"]);
      $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
      $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
      return $pdo;
    }
    catch (PDOException $exception)
    {
      die("Blad polaczenia z baza danych (new).");
    }
  }

  public static function query($query, $params = array())
  {
    $connection = self::connect();
    $statement = $connection->prepare($query);
    $statement->execute($params);
    $data = $statement->fetchAll();
    $connection = null;
    return $data;
  }
}

But when I try to run it:

NewDatabase::query("UPDATE " . $config["NEW_DB_TABLE"] . " SET `password` = ?, `salt` = ? WHERE `username` = ?", [$cryptedPassword, $salt, self::$username]);

It returns an exception:

PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

How to make this running? I'm using fetchAll() and I've set the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

Cholewka
  • 775
  • 1
  • 8
  • 25
  • 1
    I wonder if it's because you're trying to do a fetchAll on an UPDATE query, which does not return a result set – aynber Apr 27 '21 at 14:50
  • Seems like a lot of work to parse the config and start a new connection to the db for every query. – Jason K Apr 27 '21 at 14:56

0 Answers0