Hide html img tag

Asked

Viewed 644 times

0

I have a Mysql database query in PHP where I store the path in the database and the image in a folder. The query brings the image and below a comment, only it has comments without image that displays the tag img. I wanted a way when to tag img no image, no display at all.

inserir a descrição da imagem aqui

I didn’t want the tag to appear when it was null only the comment.

  • 3

    Put how you are listing these comments. Just one IFto solve this.

3 answers

3

If from the database it returns NULL when there is no image just do so =

<?php if($img){ ?>
<img src="<?php echo $img; ?>"/>
<?php }else{ ?>
<img src="imgpadrao.jpg">
<?php } ?>

In this example I put a default image that you can put, but if you want nothing to appear, just have Else and leave only if.

1

You can use the function file_exists to check if the image path is valid, if the same means that the image exists, if it does not exist you do not need to show it on the example screen:


if (file_exists('caminho/imagem.png')) { // imagem existe
    echo "img src='caminho/imagem.png' alt='img'";
} else { // imagem não existe

}


  • 1

    I think the path for the image does not exist, nor has in the database, it would cause file_exists('') which would work but does not seem to me the most correct. The ideal would be to compare the one that comes from the database.

  • @Jorgeb. from what I understand he takes this path of db to put in the img tag, so he could check if it exists, if you do file_exists('') will not enter the existing image condition you have already tested ?

0

You can use onerror event, an event handler for runtime script errors. Follow an example:

<img 
  src="broken.png" 
  onerror="this.style.display='none'"
/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.