levi lucas
levi lucas

Reputation: 99

display no image if doesnt exist codeigniter

All i want to do is display an image if the image exist if not display blank but i cant seem to figue it out.

Im storing my image path file in my database, in the column called, file and path is stored like this: /images/file_name

now if there isnt an image being posted it stores /images/

if ($news_item['file'] = '/images/11.jpg') { ?>
        <img src="<?php echo base_url(); echo $news_item['file'] ?>">
    } else {
        echo '';
    } 

    ?>

If you need anything more of me let me know but just to give you an idea of what I'm achieving.

its a news post, if you create a post you have a title and description and you have the choice of entering in a file/image.. if you leave it blank it will enter in /images/ and if you enter an image in it will be: /images/file_name (this is inserted into a db)

Upvotes: 1

Views: 2086

Answers (3)

jrierab
jrierab

Reputation: 615

I would simply use the alt property of the image to show an alternative text:

<img src="<?php echo base_url(); echo $news_item['file'] ?>" alt="no image">

or, if you want it to be completely blank:

<img src="<?php echo base_url(); echo $news_item['file'] ?>" alt="">

EDIT: To completely remove the image, you can conditionally generate the image or an alternative text:

if (file_exists($news_item['file'])) {
    echo '<img src="'.base_url().$news_item['file'].'">';
} else {
    echo "No image";
}

Upvotes: 1

Shafeeque
Shafeeque

Reputation: 2069

I suggest you to store the default.jpg in DB ( You can set this default in DB ). And store the default.jpg image in image folder. So that you don't need to change anything in coding.

Upvotes: 0

Nil&#39;z
Nil&#39;z

Reputation: 7475

Check like this:

if (file_exists($news_item['file'])) {

Upvotes: 1

Related Questions