jonathanl5660 jonathanl5660 - 2 months ago 10
PHP Question

PHP - Don't display empty database field remove div/image

How would I make it so for example, if there isn't a mobile number for an entry the mobile icon will not show up maybe removing the div?

if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)) {
echo "<div class='result-container'>

<div class='titlebox'>
<h2>" . $row['name'] . "</h2>
<p><strong>" . $row['services'] . "</strong></p>
<div class='iconbox'>
<a href='" . $row['tel'] . "'><img src='img/icons/phone.png' ></a>
<a href='" . $row['mob'] . "'><img src='img/icons/mobile.png' ></a>
<a href='mailto:" . $row['email'] . "'><img src='img/icons/email.png' ></a>
<a href='" . $row['web_url'] . "'><img src='img/icons/web.png' ></a>
</div>
</div>

</div>";
}
}
}
else
echo "<h3>No results found </h3>";

mysql_close(); ?>

Answer

You could check whether it is empty() or not:

" . ((empty($row['mob'])) ? '' : "<a href='" . $row['mob'] . "'><img src='img/icons/mobile.png' ></a>") . "

Read here why you might want to choose empty() over alternative methods like !=.