Home PHP

PHP: Display Image from Database

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.

database:

CREATE TABLE IF NOT EXISTS `images` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) NOT NULL,
  `data` blob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;

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

<html>
    <head>
        <title>MySQLi Tutorial</title>
    </head>
<body>
    <div>Here’s the image from the database:</div>
    <!– “1” is the database id of the image to be selected –>
    <img src=”source.php?id=1” />
</body>
</html>

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

<?php
//include database connection
include ‘db_connect.php’;
//select the image
$query = “select * from images WHERE id = ?”;
$stmt = $con->prepare( $query );
//bind the id of the image you want to select
$stmt->bindParam(1, $_GET['id']);
$stmt->execute();
//to verify if a record is found
$num = $stmt->rowCount();
if( $num ){
    //if found
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
   
    //specify header with content type,
    //you can do header(“Content-type: image/jpg”); for jpg,
    //header(“Content-type: image/gif”); for gif, etc.
    header(“Content-type: image/png”);
   
    //display the image data
    print $row['data'];
    exit;
}else{
    //if no image found with the given id,
    //load/query your default image here
}
?>

I got this output:

PHP: Display Image from Database

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

width=’300′ height=’300′ />

If you want to download this code:

DOWNLOAD SOURCE CODE