We help IT Professionals succeed at work.

Php/MySQL display a default image if the MySQL file image blob is empty

BenzGuy
BenzGuy asked
on
465 Views
Last Modified: 2013-12-12
This should be a fairly easy question for you those of you familiar with PHP, but I am not having any luck finding an answer.  I've already search through-out EE and nothing has worked and I'm running out of time.

What I'm trying to do, is to display a default image if the MySQL file image blob is empty

Thanks in advance for any help you can provide
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
	header('Content-Type: image/jpg');
	header("Content-Disposition: attachment; filename=photo.jpg");
	
	if (!empty($data['file'])) { echo "<img src =\"<img src="nophoto.jpg" />";
	}	
	else {
    	echo $data['file'];
	} 
?>

Open in new window

Comment
Watch Question

Author

Commented:
By the way, the code below works perfect, so I believe there's an issue with the if  / else satement.
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
	header('Content-Type: image/jpg');
	header("Content-Disposition: attachment; filename=photo.jpg");
 
    	echo $data['file'];
?>
 

Open in new window

Shouldn't this:

if (!empty($data['file'])) { echo "<img src =\"<img src="nophoto.jpg" />";

be:

if (!empty($data['file'])) { echo "<img src=\"nophoto.jpg\" />";

?

Sorry if I am missing something totally obvious -- just learning php, but figured since noone's answering and you're in a rush I'd give it a whack...

Author

Commented:
Thanks for the help, but it didn't work :(  


hmm.

If you just type

<img src="nophoto.jpg" />

straight into your html somewhere, does the image show up?

also, the ! means 'not' right?

so isn't

if (!empty($data['file']))

saying "if NOT empty"?

try removing the !
in other words, the line might be

if (empty($data['file'])) { echo "<img src=\"nophoto.jpg\" />";

also try

if (empty($data)) { echo "<img src=\"nophoto.jpg\" />";



This is assuming that the html test to display the image works.
What actually does happen, do you get an error, or do you get the Missing Image icon?

Author

Commented:
Thank you very much for the help, I am a total noob, so please bear with me.  

You are definetly on to something here.

See the code below:





   
	if (!empty($data)) { echo $data['file'];	
	}
This part now works - thanks for the ! NOT Tip, that worked like a charm.
 
The below code however still needs help
	else {
	echo "<img src=\"nophoto.jpg\" />";
	} 
I'm not exactly sure how to display the nophoto.jpg file within this script 

Open in new window

outside of the php tags (so before the <?php in the beginning or after the ?> at the end), type

<img src="nophoto.jpg" />

That is just plain HTML and should bring up the nophoto.jpg image, if it exists.

are you sure you got the path right? It's not like "images/nophoto.jpg"?

because just having the image name implies that that you have that image right inside your main root folder, which is not standard practice...

Author

Commented:
For this test, the image is in the same folder (just to ensure it worked) .  

Outside the php tags <img src="nophoto.jpg" /> works just fine.  

I just need it to display in place of the other photo if the image blob field is null

Author

Commented:
Actually, this part isn't working like I thought it was.

      if (!empty($data)) { echo $data['file'];      

Author

Commented:

if (!empty($data)) { echo $data['file'];      
This will display the photo if one exists just fine works good

If I change it to this (taking out the !)
if (empty($data)) { echo $data['file'];      

It should display the photo on the fields that are blannk, correct?  

or am I missing something simple?

Author

Commented:
Sorry, I guess that cannot happen since there's no photo there in the fist place.  

Author

Commented:
So the only remaining issue, is the else syntax.  Although everything I've read so far looks like this is correct.

      else
      {
      echo "<img src=\"nophoto.jpg\" width=\"500\" height=\"500\" />";
      }  

yeah, if the feed from the DB is coming in fine when there IS an image, the only other thing is the else

 echo "<img src=\"nophoto.jpg\" />";

this should be all that you need, assuming:

1. nophoto.jpg exists
2. it's not in some subfolder, but in the main root folder of the site

Author

Commented:
The nophoto.jpg definetly exists and it's in the same folder, so there should be no issues there.  (I'm familiar with HTML, just new to PHP)

Here is a code snippet from the code that I am using to display the final results, so it may be that there is something wrong here then.

The complete code for the download-view.php file is what is listed above in my original post.
<div align="center">
<td width="500" class="dr"><?php echo htmlspecialchars("Before")."&nbsp;" ?>
<div align="center">
<img src="download-view.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%">
</div></td>
<td width="500" class="dr"><?php echo htmlspecialchars("After")."&nbsp;" ?>
<div align="center"><img src="download-view2.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%" /></div></td>

above that code, put


<img src="nophoto.jpg" />

and see if the image shows up with just straight html

Author

Commented:
The photo shows up using straight html
hmm put up all the php code again

Author

Commented:
The index.php page is using the code to display the photo generated from the download-view.php file - I am only concerned with the photo being produced from the download-view.php file for now. If I can get it to work for download-view.php it should be easy to fix download-view2.php

The problem has to be in the use of the if and else statements in the download-view.php file.  


index.php code snippet
 
<div align="center">
<td width="500" class="dr"><?php echo htmlspecialchars("Before")."&nbsp;" ?>
<div align="center">
<img src="download-view.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%">
</div></td>
<td width="500" class="dr"><?php echo htmlspecialchars("After")."&nbsp;" ?>
<div align="center"><img src="download-view2.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%" /></div></td> 
 
___________________________________________________________________________________________
 
download-view.php Code
 
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
	header('Content-Type: image/jpg');
	header("Content-Disposition: attachment; filename=photo.jpg");
	
	if (!empty($data['file'])) { echo "<img src =\"<img src="nophoto.jpg" />";
	}	
	else {
    	echo $data['file'];
	} 
?>

Open in new window

Author

Commented:
To test it I put the  "echo $data['file'];" in place of the echo "<img src =\"<img src="nophoto.jpg" />"; and that part seemed to have worked.

When changing this part of the code it works fine (because there's no else statement)

      if (!empty($data['file'])) {     echo $data['file'];
      }      

And removing the ! makes the photo go away, so I do believe that part is working
<img src="download-view.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%">
 
that line seems fishy... try:

<img src="download-view.php?recid=<?php echo "htmlspecialchars($row['id'])" ?>" width="100%">
same with the line further down

not sure if it's supposed to be this way, but that one references
download-view2.php

not

download-view.php

Author

Commented:
That actually kills the entire page - nothing displayed at all - blank screen
Currently your code is:

if (!empty($data['file'])) { echo "<img src =\"<img src="nophoto.jpg" />";
        }      
        else {
        echo $data['file'];
        }

Shouldn't it be the reverse:

if (!empty($data['file'])) {echo $data['file'];
        }      
        else {
         echo "<img src =\"<img src="nophoto.jpg" />";
        }


What about this:


or remove the ! from your code...
err disregard the

"What about this:"

from my previous post.. forgot to erase that.
oh wait
 try this:

if (!empty($data['file'])) {echo $data['file'];
        }      
        else {
         echo "nophoto.jpg";
        }
and undo all that crap that I wrote that made the page go blank, of course.
dang. that made no sense.

Okay let me put it like this:     : )

if this:

if (!empty($data['file'])) {echo $data['file'];
        }      
        else {
         echo "<img src=\"nophoto.jpg\" />";
        }

doesn't work, you're probably gonna have to wait for someone who actually knows this stuff well to come along, because that seems to me to be correct, but I don't know very much.
Sorry can't be of more help, I just started learning this stuff (as well as HTML) a month and a half ago by asking questions just like this on EE : )

Author

Commented:
sorry, that did not work either

Thanks for the help though

Author

Commented:
I really believe it IS correct, I just think there may be something going on earlier in the code or something to do with the sending the header etc..

I do appreciate what you've submitted as it helped to make me think a bit more about it.    

Anyway, thanks again!
wait, try this:

get rid of that entire if/else statement and just put

echo "<img src=\"nophoto.jpg\" />";



what happens then?



so the code being:
download-view.php Code
 
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
        header('Content-Type: image/jpg');
        header("Content-Disposition: attachment; filename=photo.jpg");
        
        echo "<img src=\"nophoto.jpg\" />";
?>

Open in new window

Author

Commented:
You're as bad as me, with having to track down a solution....  LOL   <greatly appreciated>  

echo "<img src=\"nophoto.jpg\" />";

Does NOT display the photo, so this is where the issue is

hmmm
okay on the download-view.php try this code and test that page (download-view.php) in the browser.

it should bring up the img, cause it's straight html..
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
        header('Content-Type: image/jpg');
        header("Content-Disposition: attachment; filename=photo.jpg");
?>
 
<img src="nophoto.jpg" />

Open in new window

Author

Commented:
it does display the nophoto.jpg photo!
ooookay try that same line w single quotes...

like this:

<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
        header('Content-Type: image/jpg');
        header("Content-Disposition: attachment; filename=photo.jpg");
        
        echo "<img src='nophoto.jpg' />";
?>

Open in new window

Author

Commented:
hmm.... still no go

Author

Commented:
I'm wondering if the header Content-Type section can display the photo like this as it's not really an attachment now it's an inline image.

        header('Content-Type: image/jpg');
        header("Content-Disposition: attachment; filename=photo.jpg");

????  

I think it's something with our syntax.. I tried on my site to just write this:

<?php echo "<img src=\"img/Connecticut.jpg\" /> "; ?>

and it displays:

"; ?>

I have no idea why...

This:

<img src="img/Connecticut.jpg" />

brings up an image...


I think my brain is fried because something obvious is missing here.. will think some more and get back to you, if you don't find it by then.

Author

Commented:
Thanks a lot for your help!

I've been trying a few things as well and still no luck, so maybe it's time to take a break

 
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
I totally agree!  

Thanks again for you help!

Sure. I'll let you know if I think up anything else. Good luck!

Commented:
Try this for "download-view.php"  You are only capturing the the file name correct?
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query       
    $query = "SELECT `file` FROM `testing` WHERE `id`='$recid' LIMIT 1";
    $result = @mysql_query($query);
    if ($result && @mysql_num_rows($result) > 0)
    {
        while($data = mysql_fetch_array($result))
        {
            if (empty($data['file'])) 
            { 
                $img = '<img src="nophoto.jpg" alt="" title="" />';
            }       
            else 
            {
                $img = '<img src="'. $data['file'] .'" alt="" title="" />';
            }
        }
        print $img;
    }
    else
    {
        print "Nothing to Display...";
    }
 mysql_close($link);

Open in new window

Author

Commented:
Deane, thank you for the reply, I will try it in a little while (at diner ATM).

Author

Commented:
Deane,

The above still doesn't work. :(  

I am using the "download-view.php" script to actually pull the photo out of the database (blob) in the background, based upon ID, then display it on a my main page (the index.php page).  

By using the code listed below everything appears to work fine. I just want to enable a default image if there is no image in the database blob to retrieve. Which I thought would be fairly straight forward, but I guess not.  

Sorry for the delay in responding, I had to set everything up again here at home to do the testing, as my original post was from work.  

Thanks for your help.  




index.php code snippet
 
<div align="center">
<td width="500" class="dr"><?php echo htmlspecialchars("Before")." " ?>
<div align="center">
<img src="download-view.php?recid=<?php echo htmlspecialchars($row["id"]) ?>" width="100%">
</div></td>
 
 
___________________________________________________________________________________________
 
download-view.php Code
 
<?php
    if (isset($_GET['recid']))
    {
        $recid = $_GET['recid'];
    }
 
    $link = mysql_connect('localhost', 'user', 'pass');
    mysql_select_db('testing', $link);
 
    // Make SELECT query
    $data = mysql_fetch_array(mysql_query("SELECT `file` FROM `testing` WHERE `id` = '{$recid}'", $link), MYSQL_ASSOC);
 
    // Set the content type header
        header('Content-Type: image/jpg');
        header("Content-Disposition: attachment; filename=photo.jpg");
        echo $data['file'];
?>

Open in new window

Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Wow Deane,

You are amazing!  That Worked Perfect!  

Now all I am looking to do, is to show something that says - "No Image Available".

Can I just create it in photoshop, then copy and paste the ASCII version of it in place of what you have here? (PHP Rules)

Thank you so much!







   

Commented:
You will have to convert the image to base64 first and place it into the area where I have the current image. if you need the code to convert a file to base64 I can give you that as well.  This came from the php.net site but works perfectly.

Just replace the noimage.jpg with your image file name and make sure they are both in the same folder.
Copy the output on the screen and paste it between the quotes in the $data string making sure there are no gaps or extra spaces.
img_base64.php
 
<?php 
// Place your image file name below:
$fh = fopen('noimage.jpg', 'rb'); 
$cache = ''; 
$eof = false; 
 
while (1) { 
 
    if (!$eof) { 
        if (!feof($fh)) { 
            $row = fgets($fh, 4096); 
        } else { 
            $row = ''; 
            $eof = true; 
        } 
    } 
 
    if ($cache !== '') 
        $row = $cache.$row; 
    elseif ($eof) 
        break; 
 
    $b64 = base64_encode($row); 
    $put = ''; 
 
    if (strlen($b64) < 76) { 
        if ($eof) { 
            $put = $b64."\n"; 
            $cache = ''; 
        } else { 
            $cache = $row; 
        } 
 
    } elseif (strlen($b64) > 76) { 
        do { 
            $put .= substr($b64, 0, 76)."\n"; 
            $b64 = substr($b64, 76); 
        } while (strlen($b64) > 76); 
 
        $cache = base64_decode($b64); 
 
    } else { 
        if (!$eof && $b64{75} == '=') { 
            $cache = $row; 
        } else { 
            $put = $b64."\n"; 
            $cache = ''; 
        } 
    } 
 
    if ($put !== '') { 
        echo $put; 
    } 
} 
 
fclose($fh); 
?>

Open in new window

Author

Commented:
Thanks Deane!

I increased the total points from 250 to 500 and I figured I would give andreyman3d2k some points for the effort that was put in.  

Deane had what I was looking for, therefore got the majority of the points.

Thank a lot for the help!
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.