Hide HTML img tag

1

I have a MySQL database query in PHP where I save the path in the database and the image in a folder. The query brings up the image and below a comment, only it has comments without image that displays the img tag. I wanted a way when the img tag has no image, does not display anything.

I did not want the tag to appear when it was null just the comment.

    
asked by anonymous 28.07.2015 / 08:02

3 answers

3

If the database returns NULL when it has 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 do not want anything to appear, just have the else and leave it alone.

    
28.07.2015 / 13:30
1

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


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

}


    
28.07.2015 / 13:24
0

You can use using onerror event, an event handler for run-time script errors. Here is an example:

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