php cannot check if a PDO result is empty using empty() returns FATAL ERROR

Brook Julias picture Brook Julias · May 20, 2012 · Viewed 21.9k times · Source

I want to check whether my prepared query has returned empty or not without having to go into a loop. This is the code I have tried using:

if(empty($pQuery1->fetch(PDO::FETCH_ASSOC))){}

When I try this I get the error:

Fatal error: Can't use method return value in write context

Whether I use PDO->fetchALL or PDO->fetch I receive the same error. Should I be doing something differently?

Answer

James Skidmore picture James Skidmore · May 20, 2012

You need to assign the results to a variable, then call empty() on the variable. It's just an annoying limitation of the empty() function. See this question.

$results = $pQuery1->fetch(PDO::FETCH_ASSOC);
if (empty($results)){}