15

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();
        }
    }

    ?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
marjanos
  • 161
  • 1
  • 1
  • 3
  • 1
    `$this->pdo -> query` Ah! – DirtyBit Sep 21 '15 at 13:15
  • [->](http://php.net/manual/en/pdo.query.php#refsect1-pdo.query-returnvalues) :) – someOne Sep 21 '15 at 13:17
  • 2
    It is saying to you that you're trying to access a function named `fetch()` on an instance that is not an object, but a boolean-type. In that case, `$q`. You expect it to be an object when your query executes with successful results. When it does not, it returns a boolean **false**, which was your case, probably because of mistyping the connection method calling `query` with the wrong syntax in `->` (there are blank spaces around it). – al'ein Sep 21 '15 at 13:17
  • 1
    BTW: english output and/or comments in the code would greatly improve a reader's understanding of what you are doing. Also, some explanation of your problem besides just posting a code fragment and an error message would be great! – Xenonite Sep 21 '15 at 14:20
  • @alan-machado There is nothing illegal about the spacing when setting/accessing an object property/method, try the below to see for yourself :) `$test = new stdClass(); $test -> property = 'hello'; echo $test -> property;` – ajmedway May 10 '18 at 11:55
  • 2
    Does this answer your question? [My PDO Statement doesn't work](https://stackoverflow.com/questions/32648371/my-pdo-statement-doesnt-work) – Dharman Aug 07 '20 at 19:10

3 Answers3

14

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.

ajmedway
  • 1,492
  • 14
  • 28
  • @alan-machado There is nothing illegal about the spacing when setting/accessing an object property/method, try the below to see for yourself :) `$test = new stdClass(); $test -> property = 'hello'; echo $test -> property;` – ajmedway Sep 21 '15 at 13:45
2

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
}
Aris
  • 4,643
  • 1
  • 41
  • 38
  • 1
    Notice: Array to string conversion in C:\xampp\htdocs\repo\generator\model\database.php on line 42 Execute query error, because: Array – marjanos Sep 22 '15 at 07:32
-1

I'm not sure wheatear this is exactly the error I struggled with, but my error was due to my $con variable, I used a single $con for 2 SQL statements, for example:

 $con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";

$stm = $con->prepare($sql);
$stm->execute();

and

 $sql1 = "INSERT INTO posts 
         VALUES('$email','$body')";


$stm1 = $con->prepare($sql1);


if ($stm1->execute()) {

I should have done:

$con = new mysqli($host,$username,$password,$database);
$sql = "SELECT name FROM users WHERE email = '$email'";

$stm = $con->prepare($sql);
$stm->execute();

and

$con1 = new mysqli($host,$username,$password,$database);

     $sql1 = "INSERT INTO posts 
             VALUES('$email','$body')";

    $stm1 = $con1->prepare($sql1);

    $stm1->execute()
Hossein
  • 37
  • 6