K
K
Kristina87872020-05-26 13:41:10
PHP
Kristina8787, 2020-05-26 13:41:10

Why does Call to a member function prepare() on null give an error?

Good day. I ran into a problem, a very simple code, but for some reason it gives an error and does not return the result of the query, I've been staring at the screen for an hour, but I can't find the error, here is the database connection file and the query method inside it

namespace App;

class Db
{
  protected $dbh;

  public function __construct()
  {
    $config = (include __DIR__.'/../config.php')['db'];
    $options = [
      \PDO::ATTR_ERRMODE  => \PDO::ERRMODE_EXCEPTION,
      \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
      \PDO::ATTR_EMULATE_PREPARES => false,
    ];
    $dsn = 'mysql:host=' . $config['host'] .'; dbname=' . $config['dbname'];
    $this->$dbh = new \PDO($dsn, $config['login'], $config['password'], $options);
  }

  public function query(string $sql, array $data = [])
  {
    $sth = $this->dbh->prepare($sql);
    $sth->execute($data);
    return $sth->fetchAll();
  }


}


then on the main page I check the performance of such a banal and simple method

require_once __DIR__.'/autoload.php';

$db = new \App\Db();


$data = $db->query('SELECT * FROM about');
var_dump($data);


as a result, I get the error Fatal error: Uncaught Error: Call to a member function prepare() on null in Db.php:22
The connection itself is being created, there are no errors.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Aksentiev, 2020-05-26
@Kristina8787

$this->$dbh
$this->dbh
find 5 differences
And if the connection to the database does not happen for some other reason, it will be the same.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question