Answer the question
In order to leave comments, you need to log in
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();
}
}
require_once __DIR__.'/autoload.php';
$db = new \App\Db();
$data = $db->query('SELECT * FROM about');
var_dump($data);
Answer the question
In order to leave comments, you need to log in
$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 questionAsk a Question
731 491 924 answers to any question