Chew Zai
Chew Zai

Reputation: 39

PDO error: $pdo->prepare()->execute() throws err "Call to a member function fetch() on boolean"

If my pdo query like:

$sql=$pdo->prepare('select timezone from wo_users where user_id=?')->execute(array($wo['user']['user_id']));
while($row=$sql->fetch()){var_dump($row);die;}

Will throw an error:

( ! ) Fatal error: Call to a member function fetch() on boolean in C:\wamp64\www\community.voyance\2\sources\calendar.php on line 27

But if my pdo query that uses query() directly will not throw error:

$sql=$pdo->query('select timezone from wo_users where user_id=1;');
while($row=$sql->fetch()){var_dump($row);die;}

C:\wamp64\www\community.voyance\2\sources\calendar.php:27: array (size=1) 'timezone' => string '-8' (length=2)

Why is this happening? Thanks!

Upvotes: 0

Views: 1032

Answers (1)

user3783243
user3783243

Reputation: 5224

You need a PDOStatement to fetch, execute only returns true or false. You should only execute the PDOStatement. That will give you back a result object you can fetch or an error. For PDO error handling see My PDO Statement doesn't work.

$stmt = $pdo->prepare('select timezone from wo_users where user_id=?');
$stmt->execute(array($wo['user']['user_id']));
while($row = $stmt->fetch()){
     var_dump($row);
     die;
}

As you can see from the manual query works because:

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

where as execute:

Returns TRUE on success or FALSE on failure.

the prepare is what we need:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

and fetch (this one is the description, not the return):

Fetches a row from a result set associated with a PDOStatement object

Upvotes: 2

Related Questions