drftorres
drftorres

Reputation: 237

Hide non-existing image from page using echo function

I have the following line:

<td><img src="Photos/<? echo $rows['photo1']; ?>" height="200" /></td>

I don't always have a photo. I would like to hide the image space. It looks like it is broken or if the url is wrong.

Upvotes: 0

Views: 212

Answers (3)

d-_-b
d-_-b

Reputation: 23161

To have no <img> tag appear for blank values, I'd use something like this:

<?php if (($rows['photo1'] !== "") || ($row['photo1'])) 
      {
       echo "<td><img src='Photos/" . $rows['photo1'] . "' height='200' /></td>";
      }
?>

if (image is not blank, and it exists) { then, echo the img tag and the variables }


Alternatively, If you want to display a different image for blank values:

<td>
     <img src="Photos/<?php if ($rows['photo1'] !== ""){echo $rows['photo1'];}
                     else {echo "defaultimg.jpg";}?>" height="200" />
</td>

Hope this helps :)

Upvotes: 1

Brett
Brett

Reputation: 3316

Perhaps this is more to your liking:

 <img src="Photos/<? echo $rows['photo1']; ?>" height="200" onerror="this.style.display='none'" />

It sets the image to not show when there is a problem (such as a broken URL).

This has the advantage of avoiding ternaries, separates PHP from HTML, and keeps things clear without excessive documentation. Hope it helps.

Upvotes: -1

Martin
Martin

Reputation: 1392

<td><?php echo (!empty($rows['photo1']) ? '<img src="Photos/' . $rows['photo1'] . '" height="200" />' : '') ?></td>

Upvotes: 2

Related Questions