Search code examples
phpsqlif-statementis-empty

Why is IF !empty() function responding to on-page values but not from database?


I would like to echo a fields value from the db if it's ISSET(). When I test the following code with set and not set values from the same page, it works fine.

if (!empty($row['YY'])) {
    echo $row['YY'];
} else {
    echo "N/A";} 

This displays a "YES"

$row['YY'] = 'YES';

And this displays an "N/A"'

$row['YY'] = '';

However, when use the same code for a fetched query from the db, the set value is correctly displayed, BUT an empty field is displays nothing at all. How do I get an empty field to display the ELSE command of "N/A"?

Also, the column I am fetching from, is NOT set to NULL. (In case that's relevant.) And I have tried with the following functions unsuccessfully as well; empty(), isset(), !isset()


Solution

  • If there is an empty string in your $row['YY'] it would return true on ! empty() check.

    To reproduce above problem:

    $row  = array('YY' => ' ');
    
    if ( ! empty($row['YY'])) {
       echo 1;
    }
    

    Prints 1 on screen

    So add trim() function to remove white space:

    $row['YY'] = trim($row['YY']);