PDO: Call to a member function fetch() on a non-object? [duplicate]

I am just trying out PDO and I get this error, Fatal error: Call to a member function fetch() on a non-object, but isn't it already on the $this->db object?

class shoutbox {

    private $db;

    function __construct($dbname, $username, $password, $host = "localhost" ) 
    { # db conections
        try {
            $this->db = new PDO("mysql:host=".$hostname.";dbname=".$dbname, $username, $password);
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    function getShouts()
    {
        $sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, time FROM shouts WHERE pmuserid == 0');

        return $sql_shouts->fetch(PDO::FETCH_OBJ);

    }

}

Solution 1:

Look carefully at the documentation for PDO::query, particularly the "Return Values" section:

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

The important bit is "FALSE on failure". FALSE is not an object, so calling ->fetch() is bad news.

The error is probably due to your use of "==" comparison operator. In SQL, it's just "=".

You should test that the $sql_shouts is not false, and then do something smart with the error, if there was one:

<?PHP
$sql_shouts = $this->db->query('...');
if ($sql_shouts === false){
    $errorInfo = $this->db->errorInfo();
    //log the error or take some other smart action
}
return $sql_shouts->fetch(PDO::FETCH_OBJ);

Solution 2:

I would say that your query is not executing due to incorrect syntax. You should really check PDO's errorinfo static function to see if the query errored out or not.

Here is a potential correct SQL statement:

$sql_shouts = $this->db->query('SELECT shoutid, message, pmuserid, ipadress, `time` FROM shouts WHERE pmuserid = 0');

I believe Time is a reserved word in MySQL I would recommend using a different name but encasing it in backticks will alleviate that issue. 1 equal sign is used for mysql, not two. But yea, look into the errorinfo function to determine if your query failed due to a syntax error and handle it gracefully.