Main Content

Display an image from a MySQL database in a web page via PHP

Archive - Originally posted on "The Horse's Mouth" - 2006-11-22 16:48:22 - Graham Ellis

There's lots of clever scripts around to tell you how to get images in and out of databases, but nothing simple to show you the principles of including such an image via (say) PHP in a web page. So here goes.

you need TWO URLs - you need the HTML page that's going to contain the image, AND you need a second URL - PHP in my example - that's going to retrieve the image and feed it out as part of the page. You CANNOT feed out both the HTML and the image from the same http request.

Here's a sample HTML page we're going to include an image in:

<html>
<head>
<title>Demo of Database Image in a page</title>
</head>
<body>
Here is your picture:<br>
<img src=picscript.php?imname=potwoods><br>
Example by Well House Consultants
</body>
</html>


Then you need the PHP script - called picscript.php in the same directory in my example:

<?php
mysql_connect("localhost","wellho","xxxxxxx");
mysql_select_db("wellho");
$image = stripslashes($_REQUEST[imname]);
$rs = mysql_query("select * from im_library where filename=\"".
addslashes($image).".jpg\"");
$row = mysql_fetch_assoc($rs);
$imagebytes = $row[imgdata];
header("Content-type: image/jpeg");
print $imagebytes;
?>


If you want to try it out, then the HTML page is here.

Want to take this further?

As a next step, I would validate the connection after the mysql_connect, and check that an image really had been returned by the mysql_query ... substituting a default image if not.

We host a complete working example of image upload, save to database, select from database and display all via a PHP script. See article on the subject

There's a forum discussion here.