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.
Some other articles
S154 - Designing an SQL Database System FileMaker Day to Unix Time conversion Databases - when to treat the rules as guidelines Blowing our own trumpet - MySQL resources SQL - Data v Metadata, and the various stages of data selection Delegate Question - defining MySQL table relationships as you create the tables Images in a database? How big is a database? (MySQL) MySQL - licensing issues, even with using the name What a difference a MySQL Index made More HowTo diagrams - MySQL, Tomcat and Java Database design for a shopping application (MySQL) MySQL - table design and initial testing example Code quality counts This article Databases needn't be frightening, hard or expensive Database design - get it right from first principles MySQL - an FAQ MySQL - a score of things to remember Oops - I got my initial database design wrong Binary Large Objects or bars MySQL - Pivot tables H999 - Additional PHP Material Image indexer / thumbnail display scripts in PHP Catchable fatal error in PHP ... How to catch, and alternative solutions such as JSON Arrays of arrays - or 2D arrays. How to program tables. Exception handling in PHP If nothing, make it nothing. Extra PHP Examples PHP Techniques - a workshop Flipping images on your web page Script to present commonly used images - PHP Copyright and theft of images, bandwidth and members. More PHP sample and demonstration programs Ordnance Survey Grid Reference to Latitude / Longitude Converting from postal address to latitude / longitude Controlling and labelling Google maps via PHP PHP Standalone - keyboard to screen Drawing hands on a clock face - PHP Drawing dynamic graphs in PHP Sorting people by name in PHP Parallel processing in PHP Dates, times, clickable diarys in PHP This article Syntax checking in PHP Reporting on the 10 largest files or 10 top scores PHP - a team member leaves Check your user is human. Have him retype a word in a graphic Hot answers in PHP Presentation, Business and Persistence layers in Perl and PHP PHP Image viewing application PHP - setting sort order with an associative array Merging pictures using PHP and GD Running a Perl script within a PHP page Double Dollars in PHP Stand alone PHP programs Time calculation in PHP the array returned by preg_match_all More maps Ordnance Survey - using a 'Get a map' What and why for the epoch PHP and natural sorting H309 - Maps, Graphics and Geographics Image indexer / thumbnail display scripts in PHP Adding a PHP build option, rotating an image based on camera data, and a new look at thumbnails in PHP The changing face of Christmas Where are you? How to write a geosensitive application Fpdf - generating .pdf documents easily from your PHP program QR codes with marketing logos embedded QR codes - graphics images that provide quick phone links UK Mapping Data - and more to come - under government Open Data measures Needle in a haystack - finding the web server overload Computer Graphics in PHP - World (incoming data) to Pixel (screen) conversion Finding and diverting image requests from rogue domains An image from a website that occasionally comes out as hyroglyphics Server logs - drawing a graph of gathered data Protecting your images from use out of context Uploading a document or image to its own URL via a browser Redirecting to your main domain for correct security keys Reducing image size on digital photos - PHP Dynamic / changing images on your web page Geocoding - converting address to latitude / Longitude with PHP via Google World Flags in your PHP pages Images for Christmas Making it all worthwhile Ever had One of THOSE mornings? Dynamic maps / geographics in PHP All around the world? addslashes v mysql_real_escape_string in PHP Gant charts - drawing them with a PHP script Ordnance Survey Grid Reference to Latitude / Longitude Converting from postal address to latitude / longitude Controlling and labelling Google maps via PHP Drawing hands on a clock face - PHP Drawing dynamic graphs in PHP This article PHP Image viewing application Merging pictures using PHP and GD Ordnance Survey - using a 'Get a map' H113 - Using MySQL Databases in PHP Pages Moving from mysql to mysqli - simple worked example What FGW passengers want to talk about / and PHP programming to find out MySQL, MySQLi, PDO or something else - how best to talk to databases from PHP How to display information from a database within a web page An example of an injection attack using Javascript The future of MySQL MySQL stored procedures / their use on the web from PHP Using print_r in PHP to explore mysql database requests Helping new arrivals find out about source code examples Grouping rows for a summary report - MySQL and PHP Setting up a MySQL database from PHP Keeping PHP code in database and running it Uploading to a MySQL database through PHP - examples and common questions Dates, times, clickable diarys in PHP What is an SQL injection attack? This article Paging through hundreds of entries Viewing images held in a MySQL database via PHP Database design - get it right from first principles Checking for MySQL errors Saving a MySQL query results to your local disc for Excel Giving the researcher power over database analysis MySQL - an FAQ mysql_connect or mysql_pconnect in PHP? G912 - Photography for the Web That spec is a kingfisher ... How far is something pictured from the camera? Catering in Syracuse, the Saigon Cafe, stolen images and Christmas Hotlinked images onto adult material sites Re-using our pictures Leaping dog, Leaping horse, copyright of old masters Trowbridge - a missed opportunity? Melksham - into the breach? Comparison - with and without flash Old pictures and comparisons What colour is the season? Ongoing Image Copyright Issues, PHP and MySQL solutions Using PHP to upload images / Store on MySQL database - security questions Drawing hands on a clock face - PHP What shape is your shake? Themes for the web site PHP Image upload script Telling a story in different ways This article My projector has a photo-id PHP Image viewing application Merging pictures using PHP and GD Keep that image small The relevance of the hairy woodpecker Published Photographer What makes a professional photographer?