PHP: Display Image from Database

Photo of Mike Dalisay
Modified Thursday, January 26, 2012
by - @ninjazhai
PHP Quick Tip: Someone asked me how to display an image stored in a MySQL database using PDO. Here’s how I did it. In this code, we will use two files – index.php and source.php and a database table with sample image data stored.

Please note that I used BLOB data type for storing my images, it can handle up to 64KiB of data. If you want larger storage for each of your images, you can use LONG BLOB that can handle up to 2,048KiB of data.


  2.   `id` int(11) NOT NULL AUTO_INCREMENT,
  3.   `name` varchar(32) NOT NULL,
  4.   `data` blob NOT NULL,
  5.   PRIMARY KEY (`id`)

index.php – This will call the image rendered by source.php using the <img> tag. The code goes like this:

  1. <html>
  2.     <head>
  3.         <title>MySQLi Tutorial</title>
  4.     </head>
  5. <body>
  6.     <div>Here's the image from the database:</div>
  7.     <!-- “1” is the database id of the image to be selected -->
  8.     <img src=”source.php?id=1/>
  9. </body>
  10. </html>

source.php – This will do the query of selecting the image based on the given ID parameter. PDO code look something like this:

  1. <?php
  2. //include database connection
  3. include 'db_connect.php';
  4. //select the image
  5. $query = "select * from images WHERE id = ?";
  6. $stmt = $con->prepare( $query );
  7. //bind the id of the image you want to select
  8. $stmt->bindParam(1, $_GET['id']);
  9. $stmt->execute();
  10. //to verify if a record is found
  11. $num = $stmt->rowCount();
  12. if( $num ){
  13.     //if found
  14.     $row = $stmt->fetch(PDO::FETCH_ASSOC);
  16.     //specify header with content type,
  17.     //you can do header("Content-type: image/jpg"); for jpg,
  18.     //header("Content-type: image/gif"); for gif, etc.
  19.     header("Content-type: image/png");
  21.     //display the image data
  22.     print $row['data'];
  23.     exit;
  24. }else{
  25.     //if no image found with the given id,
  26.     //load/query your default image here
  27. }
  28. ?>

I got this output:

PHP: Display Image from MySQL Database
Click to enlarge.

How to resize this image output? You can just do it the normal way, for instance:

<img src='source.php?id=1' width='300' height='300' />

If you want to download this code:

The Code of a Ninja Resources

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.