I get a fatal error on executing the query below:
$stmt = $db->query('SELECT * FROM comments LIMIT 50');
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $result['name'] . ':' . strip_tags($result['message']);
}
Returns:
Fatal error: Call to a member function query() on a non-object
I set my $db like this:
try {$db = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');}
catch(PDOException $e) {echo $e->getMessage();}
Does anyone know what causes this error?
You are not getting an error because of the execution of the query. The query in fact will never try to execute
This error –
tells you that
$dbis not an object.Either it was never instantiated, or it was instantiated within a different scope.