Checking for an empty result (PHP, PDO, and MySQL)

PhpMysqlPdo

Php Problem Overview


What am I doing wrong here? I'm simply retrieving results from a table and then adding them to an array. Everything works as expected until I check for an empty result...

This gets the match, adds it to my array and echoes the result as expected:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today', $today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'];
    echo $row['id_email'];
}

$db = null;
return true;

When I try to check for an empty result, my code returns 'empty', but no longer yields the matching result:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

if ($sth->fetchColumn()) {
    echo 'not empty';
    while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
        $this->id_email[] = $row['id_email'];
        echo $row['id_email'];
    }
    $db = null;
    return true;
}
echo 'empty';
$db = null;
return false;

Php Solutions


Solution 1 - Php

You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there are any results. You do

if ($sth->rowCount() > 0) {
  ... got results ...
} else {
   echo 'nothing';
}

Relevant documentation is here: PDOStatement::rowCount

Solution 2 - Php

If you have the option of using fetchAll() then, if there are no rows returned, it will just be an empty array.

count($sql->fetchAll(PDO::FETCH_ASSOC))

will return the number of rows returned.

Solution 3 - Php

You should not use rowCount for SELECT statements as it is not portable. I use the isset function to test if a select statement worked:

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

// I would usually put this all in a try/catch block, but I kept it the same for continuity
if(!$sth->execute(array(':today'=>$today)))
{
    $db = null;
    exit();
}

$result = $sth->fetch(PDO::FETCH_OBJ)

if(!isset($result->id_email))
{
    echo "empty";
}
else
{
    echo "not empty, value is $result->id_email";
}

$db = null;

Of course this is only for a single result, as you might have when looping over a dataset.

I thought I would weigh in as I had to deal with this lately.

Solution 4 - Php

$sql = $dbh->prepare("SELECT * from member WHERE member_email = '$username' AND member_password = '$password'");

$sql->execute();

$fetch = $sql->fetch(PDO::FETCH_ASSOC);

// if not empty result
if (is_array($fetch))  {
    $_SESSION["userMember"] = $fetch["username"];
    $_SESSION["password"] = $fetch["password"];
    echo 'yes this member is registered'; 
}else {
    echo 'empty result!';
}

Solution 5 - Php

> what I'm doing wrong here?

Almost everything.

$today = date('Y-m-d'); // no need for strtotime

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR

$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while

return count($this->id_email); // no need for the everything else

Effectively, you always have your fetched data (in this case in $this->id_email variable) to tell whether your query returned anything or not. Read more in my article on PDO.

Solution 6 - Php

One more approach to consider:

When I build an HTML table or other database-dependent content (usually via an AJAX call), I like to check if the SELECT query returned any data before working on any markup. If there is no data, I simply return "No data found..." or something to that effect. If there is data, then go forward, build the headers and loop through the content, etc. Even though I will likely limit my database to MySQL, I prefer to write portable code, so rowCount() is out. Instead, check the the column count. A query that returns no rows also returns no columns.

$stmt->execute();
$cols = $stmt->columnCount(); // no columns == no result set
if ($cols > 0) {
    // non-repetitive markup code here
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

Solution 7 - Php

Thanks to Marc B's help, here's what worked for me (note: Marc's rowCount() suggestion could work too, but I wasn't comfortable with the possibility of it not working on a different database or if something changed in mine... also, his select count(*) suggestion would work too, but, I figured because I'd end up getting the data if it existed anyway, so I went this way).

$today = date('Y-m-d', strtotime('now'));

$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");

$sth->bindParam(':today', $today, PDO::PARAM_STR);

if(!$sth->execute()) {
    $db = null;
    exit();
}

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $this->id_email[] = $row['id_email'];
    echo $row['id_email'];
}
$db = null;

if (count($this->id_email) > 0) {
    echo 'not empty';
    return true;
}
echo 'empty';
return false;

Solution 8 - Php

I only found one way that worked...

$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");

//if (!is_array($quote)) {  didn't work
//if (!isset($quote)) {  didn't work

if (count($quote) == 0) {   //yep the count worked.
	echo 'Record does not exist.';
	die;
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncanoebrainView Question on Stackoverflow
Solution 1 - PhpMarc BView Answer on Stackoverflow
Solution 2 - Phpjosh123a123View Answer on Stackoverflow
Solution 3 - PhpstubsthewizardView Answer on Stackoverflow
Solution 4 - PhpMahmoud AliView Answer on Stackoverflow
Solution 5 - PhpYour Common SenseView Answer on Stackoverflow
Solution 6 - PhplangoView Answer on Stackoverflow
Solution 7 - PhpcanoebrainView Answer on Stackoverflow
Solution 8 - PhphamishView Answer on Stackoverflow