Fetch () member function call for boolean

I get this error:

Fatal error: call fetch () member function in boolean in C: \ xampp \ htdocs \ repo \ generator \ model \ database.php on line 34

When I run this code:

class database { private $user = 'root'; private $pass = ''; public $pdo; public function connect() { try { $this->pdo = new PDO('mysql:host=localhost; dbname=generatordatabase', $this->user, $this->pass); echo 'Połączenie nawiązane!'; } catch(PDOException $e) { echo 'Połączenie nie mogło zostać utworzone: ' . $e->getMessage(); } } public function createTable() { $q = $this->pdo -> query('SELECT * FROM article'); while($row = $q->fetch()) { echo $row['id'].' '; } $q->closeCursor(); } } ?> 
+6
source share
2 answers

According to PHP manual for PDO :: query

PDO :: query () returns a PDOStatement or FALSE object on failure.

It looks like your query is not working (on line 33) and thus returns BOOLEAN (false), probably because at that point in time the PDO did not connect to the database, which contains a table called article . In the connect () method, I see that it is trying to connect to a db called 'generatordatabase'; make sure that this connection is completed before calling createTable (); otherwise, make sure that it contains a table called "article".

I would recommend adding a few more code examples, for example code that calls this class / method before the error runs.

+6
source

Some error handling will help you avoid these problems:

 $q = $this->pdo->query('SELECT * FROM article'); //error case if(!$q) { die("Execute query error, because: ". print_r($this->pdo->errorInfo(),true) ); } //success case else{ //continue flow } 
+1
source

All Articles