Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 998
Brook Julias Avatar asked May 20 '12 21:05

Brook Julias


People also ask

How to use fetchAll in PHP?

The fetch_all() / mysqli_fetch_all() function fetches all result rows and returns the result-set as an associative array, a numeric array, or both. Note: This function is available only with MySQL Native Driver.

How to FETCH array in PHP PDO?

PDOStatement::fetchAll() returns an array containing all of the remaining rows in the result set. The array represents each row as either an array of column values or an object with properties corresponding to each column name. An empty array is returned if there are zero results to fetch.

What is PDO method in PHP?

The PHP Data Objects (PDO) defines a lightweight interface for accessing databases in PHP. It provides a data-access abstraction layer for working with databases in PHP. It defines consistent API for working with various database systems.


1 Answers

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)){}
like image 105
James Skidmore Avatar answered Sep 28 '22 11:09

James Skidmore