Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call to a member function fetch() on boolean [duplicate]

Tags:

php

pdo

I receive this error:

Fatal error: Call to a member function fetch() on 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();
        }
    }

    ?>
like image 500
marjanos Avatar asked Sep 21 '15 13:09

marjanos


2 Answers

As per the PHP manual for PDO::query

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

It looks like your query is failing (on line 33) and thus returning a BOOLEAN (false), likely because at that point in execution, PDO has not connected to a database that contains a table called article. In the connect() method I see that it tries to connect to a db called 'generatordatabase'; ensure this connection is being made prior to calling createTable(), otherwise ensure that it contains a table called 'article'.

I would recommend adding some more code examples, for instance the code that calls this class/method before the error is triggered.

like image 109
ajmedway Avatar answered Oct 15 '22 11:10

ajmedway


Some error handling will help you avoid issues like this:

$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
}
like image 43
Aris Avatar answered Oct 15 '22 11:10

Aris