Search code examples
phpmysqlfetchall

MySQL PHP - How to remove unnecessary php echo text when mysql field is null?


I've got a client who wants me to format a list of businesses on a website page using data from a mysql database and putting it on the web page using php.

The client wants each piece of data to be identified, like this:

Contact Person: Sue Smith
Website: greatwebsite.com

Here's the problem:

Some of the businesses don't have a website. So I do NOT want the business listing to show up like this:

Contact Person: Sue Smith
Website:

I do NOT want the Website line to show up at all if there is no website.

Here's what I've done so far - which does NOT solve the problem (truncated for brevity):

$result = mysql_query("SELECT * FROM businesses ORDER BY business");
while($field = mysql_fetch_array($result))
{
    echo
    "<h3>".$field['business']."</h3>
    <p>Website: ".$field['website']."</p>";
}

I need to learn how to delete the "Website" line entirely if there is no website.


Solution

  • A simple if will work fine:

    $result = mysql_query("SELECT * FROM businesses ORDER BY business");
    while($field = mysql_fetch_array($result))
    {
       if (! empty($field['business']) )
          echo "<h3>".$field['business']."</h3>";
    
       if (! empty($field['website']) )
          echo "<p>Website: ".$field['website']."</p>";
    }