Search code examples
phppostgresqlherokupdoheroku-postgres

PHP PDO returns true


I'm trying to pull out some data from my database, but a boolean is returned (as expected), but then when I try the variations of ->fetch(), I get the error Fatal error: Uncaught Error: Call to a member function fetch() on bool.

Somehow, it seems like the ->execute();-function saves the bool rather than the object - I'm not sure why. I think I've stared myself blind on my code?

Code

<?php
$cc = $pdo->prepare("SELECT country FROM quarter WHERE company_id = ? GROUP BY 1 ORDER BY country ASC")->execute([$_GET["id"]]);
#var_dump($cc);
var_dump($cc->fetch());
var_dump($cc->fetchAll(PDO::FETCH_COLUMN));
?>

Expected response

country
GB
NO

Actual response

Fatal error: Uncaught Error: Call to a member function fetch() on bool in [..]

Solution

  • The execute() method returns bool while prepare() returns object

    You should use fetch() method of the object itself

    $cc = $pdo->prepare("SELECT country FROM quarter WHERE company_id = ? GROUP BY 1 ORDER BY country ASC");
    
    $cc->execute([$_GET["id"]]);
    #var_dump($cc);
    var_dump($cc->fetch());