开发者

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

This question already has answers here: Why does this PDO statement silently fail? (2 answers) Closed 6 years ago.

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)
  开发者_JAVA百科      {
            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);

    }

}


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


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.


It happens when the table doesn't exist also. make sure it actually exists, and isn't just a holder in the database due to hard drive errors.

When that happens I suggest you recreate the database/table.


I got this error message due to a silly mistake with brackets. It was nested inside an if statement and just didn't see it.

db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var)->fetchField());

It took me a while to work out that I didn't close the db_query bracket in the right place. Maybe it helps someone else staring at this wondering wth. Correct:

db_query("SELECT thing FROM table WHERE var=:var", array(":var" => $var))->fetchField();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜