Skip to main content
Legend
March 11, 2014
Question

PHP PDO Conditional Image ??

  • March 11, 2014
  • 1 reply
  • 1418 views

I'm trying to elarn PHP PDO - Not sure how to conditionally show the image (blog_img) :

I'm learning PHP PDO - How do you conditionally show an image based on whether it exists? I have the code below at the moment but if no image exists for an article then there's a placeholder for broken image link..

     Code:

     $ARTICLE = $conn->prepare("SELECT blog_title, blog_article, blog_img FROM Blog WHERE blog_title=:blog_title");

     $ARTICLE->bindParam(':blog_title', $blog_title, PDO::PARAM_STR, 25);

     $ARTICLE->execute();

   <?php

     while ($r = $ARTICLE->fetch()) {

     ?>

     <h1>

        <?PHP

    echo ($r['blog_title']);

      ?>

     </h1>

      <img src="images/<?PHP echo ($r['blog_img']);?>">

       <?PHP

       echo ($r['blog_article']);

       ?>

     <?php

      }

    ?>

This topic has been closed for replies.

1 reply

Rob Hecker2
Legend
March 11, 2014

echo isset($r['blog_img'])? "<img src='images/".$r['blog_img']."'>" : NULL ;

In this code, first we check whether blog_img has a value; if it does, we echo the value inside the IMG tag, if there is no value, we echo NULL.

. . .but, don't store images in databases. Store the file names and put the images in a folder.

Paul-MAuthor
Legend
March 12, 2014

Still not working for me, it shows the image OK but when no reference to an image it still show a placeholder to a missing image

    $ARTICLE = $conn->prepare("SELECT blog_title, blog_article, blog_img FROM Blog WHERE blog_title=:blog_title");

     $ARTICLE->bindParam(':blog_title', $blog_title, PDO::PARAM_STR, 25);

     $ARTICLE->execute();

   <?php

     while ($r = $ARTICLE->fetch()) {

     ?>

     <h1>

        <?PHP

    echo ($r['blog_title']);

      ?>

     </h1>

      <?PHP echo isset($r['blog_img'])? "<img src='images/".$r['blog_img']."'>" : NULL ;?>

       <?PHP

       echo ($r['blog_article']);

       ?>

     <?php

      }

    ?>

Paul-M - Community Expert
Rob Hecker2
Legend
March 12, 2014

If that's not working, then is there some kind of value in blog_img when there is no image, or is it NULL ?

ISSET should return false for both empty string and NULL. I tested this on a blob database column and it worked, so I wonder what's going on.

. . .and I will repeat: Don't store images in databases, unless your database isn't important.