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?

1 Answer 1

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)){}
Sign up to request clarification or add additional context in comments.

7 Comments

id like to point out you might as well just do if (!$results) {} as it behaves identically.
@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. php.net/manual/en/function.empty.php
it was set on the previous line :)
@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.
@BrookJulias, the ! operator converts its operand to boolean, and empty array converts to boolean false. ! operator and empty() are 100% logically equivalent.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.