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

419 Views Asked by At

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.

3

There are 3 best solutions below

3
On BEST ANSWER

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