Harinder
Harinder

Reputation: 1257

PDO Function setFetchMode

Hello i was trying to make function with PDO but getting error (new to PDO) here is my code

    function mail_id($mail){
    global $host, $dbname, $user, $pass;
    $DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
    $STH = $DBH->query("select count(from) from messages where from = '$mail'");
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    $row = $STH->fetch();
    return $row;
}

i want to count row FROM and here is the out put i was trying

$mail=mail_id($userid);
if (0<count($mail['to_viewed'])) {echo "green";} else {echo "gray";}

this is the error

Call to a member function setFetchMode() on a non-object

please help thx

Upvotes: 0

Views: 4762

Answers (1)

CodeZombie
CodeZombie

Reputation: 5377

You need to check the return value of PDO::query(). In (ugly) PHP there are lots of functions that return a value of mixed type. In the case of PDO::query() the return type is either PDOStatement or bool, although the prototype in the documentation says something different:

Description:
PDOStatement PDO::query ( string $statement )
...

Looks like it always returns PDOStatement.

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

Oops, not in every case! Therefore you are not guaranteed that the value returned is a PDOStatement.

The correct prototype would be:

Description:
mixed PDO::query ( string $statement )
...

In your case the query is invalid (by using a reserved keyword like FROM as a column name) which results in a return value of type boolean with the value FALSE. A boolean value is not an object and therefore your call to $STH->setFetchMode() fails.

Depending on your PDO::ATTR_ERRMODE you get

  • an exception (PDO::ERRMODE_EXCEPTION), so you don't need to check the return value
  • a warning (PDO::ERRMODE_WARNING)
  • nothing (PDO::ERRMODE_SILENT), so you have to check the return value, errorCode() and errorInfo()

Upvotes: 1

Related Questions