14

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?

Brook Julias
  • 2,085
  • 9
  • 29
  • 44

1 Answers1

35

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)){}
Community
  • 1
  • 1
James Skidmore
  • 49,340
  • 32
  • 108
  • 136
  • 7
    id like to point out you might as well just do `if (!$results) {}` as it behaves identically. – goat May 20 '12 at 21:45
  • 1
    @chris if(empty($foo)) won't generate a warning if the parameter isn't set. if(!$foo) will generate a warning if the parameter isn't set. http://php.net/manual/en/function.empty.php – Jake May 20 '12 at 21:48
  • 1
    it was set on the previous line :) – goat May 20 '12 at 21:50
  • 2
    @chris - using `$results` in such a way only fails if the result returns false. It is possible to have an empty result without being false. – Brook Julias May 20 '12 at 21:51
  • That is a pretty annoying limitation. I wounder when if it will be corrected. – Brook Julias May 20 '12 at 21:53
  • 5
    @BrookJulias, the ! operator converts its operand to boolean, and empty array converts to boolean false. ! operator and empty() are 100% logically equivalent. – goat May 20 '12 at 21:54
  • @Chris - I must have messed up some of my testing. – Brook Julias May 20 '12 at 22:41