I have a script that calls up a picture stored in a database. I then have a script that displays said picture on another page. If there is no picture in the database I would like for their to be a no picture icon displayed.

New to php but I believe that some conditional statement is in order but I don't know where exactly to put it.

Here is the code to call up the picture. picscript1.php

<?php

$username = '';
$password = '';
$host = '';
$database = '';

mysql_connect($host, $username, $password) or die("Can not connect to database: ".mysql_error());

mysql_select_db($database) or die("Can not select the database: ".mysql_error());

$ID=$_GET['ID'];
$query = mysql_query("SELECT * FROM norestaurants WHERE ID='".$ID."'");
$row = mysql_fetch_array($query);
$content = $row['pic1'];


header('Content-type: image/jpg');
     echo $content;
   
?>

The code to then display the picture:

<?
$ID=$_GET['ID'];
echo "<img src='picscript1.php?ID=".$ID."' alt='$Name' width='224' height='168'>";
?>

Now I can do a conditional in picscript1.php but that would not stop the image icon from appearing. How can I do it in the second bit of code that displays the picture?

Any help will be greatly appreciated.

Thanks

Dani AI

Generated

Two solid ways to avoid the broken image icon:

  1. Decide before you print the img tag. Do a quick existence check and only render the tag (or a fallback) when there is data. This prevents the browser from ever requesting a missing image and keeps the page clean.
// page that outputs HTML
$ID = (int)$_GET['ID'];

$mysqli = new mysqli($host, $username, $password, $database);
$stmt = $mysqli->prepare('SELECT pic1 IS NOT NULL AND pic1 <> "" AS has_pic FROM norestaurants WHERE ID=? LIMIT 1');
$stmt->bind_param('i', $ID);
$stmt->execute();
$stmt->bind_result($has_pic);
$stmt->fetch();

if ($has_pic) {
    echo '<img src="picscript1.php?ID=' . $ID . '" alt="Restaurant photo" width="224" height="168">';
} else {
    // either show nothing, or a friendly placeholder
    echo '<img src="/images/CClogo.jpg" alt="No photo" width="224" height="168">';
}
  1. If you always want an img in the markup, @phpology is on the right track. Make the fallback in picscript1.php bulletproof by redirecting when there is no BLOB. This avoids header/content-type mismatches and lets the web server set headers for the static file.
// picscript1.php
// after you queried the row...
if (empty($row['pic1'])) {
    header('Location: /images/CClogo.jpg', true, 302);
    exit;
}
header('Content-Type: image/jpeg'); // set to actual MIME stored
echo $row['pic1'];
exit;

Extra tips: match the MIME type to the real image (jpeg/png/gif) and call exit after output so nothing corrupts the stream, echoing ’s point about stray output. Also cast/validate IDs and move off the old mysql_* API to mysqli/PDO. For a client-side safety net, you can add onerror to the tag: <img ... onerror="this.src='/images/CClogo.jpg'">, but keep the server-side check for reliability.

Recommended Answers

All 5 Replies

you want to check to see if content is set else readfile another default image

$content = $row['pic1'];
if($content != "")
{
//show picture from database
echo $content;
}
else
{
//show generic picture
readfile(PATH_TO_GENERIC_IMAGE);
}

I changed my script to the following but I still get the broken image. The default picture I'm trying to use is stored in the same directory as the script but the image is stored in the database.

$content = $row['pic1'];
if ($content !="")
{

header('Content-type: image/jpg');
     echo $content;
}
else
{
readfile (CClogo.jpg);   
}

Is that the correct way to to the readfile?

you want to check to see if content is set else readfile another default image

$content = $row['pic1'];
if($content != "")
{
//show picture from database
echo $content;
}
else
{
//show generic picture
readfile(PATH_TO_GENERIC_IMAGE);
}

Put the image file name in quotes: "CClogo.jpg"
Make sure that the upper/lowercase spelling of the filename is correct.
Make sure that picscript1.php does not output any characters after the image data. It's good practice to delete the closing ?> php bracket from scripts which do not output HTML.

I've done a similar task for a project. here is a code which works fine. I hope it is help. You may need to tweak a bit

//The sql statement below may need to replaced with yours as it is combination of image name in db and actual file in a folder on server

$uploaddir = "images/clientsimages/thumbs/";

$get_data = "SELECT i.uploadedfile, i.clientid "
          . " FROM images AS i, ajax_client AS a "
          . " WHERE i.clientid = a.customerid "
          . " AND a.id = $_POST[sel_id]";

$get_data_res = mysql_query($get_data) or die(mysql_error() . '<br>sql : '.$get_data); 

if (mysql_num_rows($get_data_res) > 0) 
{ 
    while ($get_data_info = mysql_fetch_array($get_data_res)) 
    { 
        $uploadedfile = $uploaddir . $get_data_info["uploadedfile"]; 

        $clientID = $get_data_info["clientid"];
        
echo "<div style=\"position: absolute; width: 124px; height: 140px; z-index: 1; left: -200px; top: 8px; background-color:#000000\" id=\"layer3\">";$display_block .="<DIV style=\"position: absolute; left: 5px; top: 6px\" name=\"cutomerimage\" id=\"cutomerimage\"><image src=\"$uploadedfile\" border=\"1\"  width=\"112\" height=\"119\"/></DIV>";
echo "</div>";

    }
}
else//begin process for inserting the default image 
{
// in the line below you can create a default image to be displayed when there is none in the db
  echo"<div style=\"position: absolute; width: 124px; height: 140px; z-index: 1; left: -200px; top: 8px; background-color:#000000\" id=\"layer3\">";  //this a frame for the image
  echo "<DIV style=\"position: absolute; left: 5px; top: 6px\" name=\"cutomerimage\" id=\"cutomerimage\"><img border=\"0\" src=\"images/default_Image3.png\" width=\"112\" height=\"119\"></DIV>"; //place the default image here
echo"</div>";
}

Hope it is of some help!
Mossa

Thanks again. Works like a charm

Put the image file name in quotes: "CClogo.jpg"
Make sure that the upper/lowercase spelling of the filename is correct.
Make sure that picscript1.php does not output any characters after the image data. It's good practice to delete the closing ?> php bracket from scripts which do not output HTML.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.