How To Display Image from Database in PHP?

PHP: Display Image from Database

Someone asked me how to display an image saved in the database in PHP. 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,048 KiB of data.

Step 1. Create a “test” database and run the following SQL code on your PhpMyAdmin.

CREATE TABLE `images` (
  `id` int(11) NOT NULL,
  `name` varchar(32) NOT NULL,
  `data` longblob NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Go to PhpMyAdmin’s insert tab to add sample data in the images table.

  • Enter ID as “1”
  • Enter Name as “sample image”.
  • Enter Data by choosing a sample image from your computer.

Step 2. Create index.php file and place the following code. This file will call the image rendered by source.php file and put it as the source of img tag.

<html>
    <head>
        <title>PHP 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>

Step 3. Create db_connect.php and place the following code. This file will connect our program to the database.

<?php
$host = "localhost";
$db_name = "test";
$username = "root";
$password = "";
 
try{
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}
 
catch(PDOException $exception){
    //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

Step 4. Create source.php file and place the following code. This will do the query of selecting the image based on the given ID parameter.

<?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
}
?>

Step 5. The output will look like the following.

PHP: Display Image from Database

Step 6. How to resize this image? You can just do it by specifying the width and height properties of of the img tag.

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

Step 7. If you want to download the code of this tutorial, use the following button.

Thank you for using our tutorial about how to display image from database in PHP!

Published
Categorized as PHP Tagged

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? You may use our comments section below or email our team at [email protected]

23 comments

  1. What if i’m updating the path to database. but when i get the path and put it in the src of the image, it dosent display anything.

    1. Hi Tyler, if the new path points to the location of the image, it will be displayed. Would you tell us your path saved in the database, image src URL and the location of your image?

    1. Hello @unmeshpt , you can store your images to a different table and provide a foreign key to your main table. This way, you can retrieve more images based from the record you queried on the main table.

  2. Hello @disqus_4cIv2bX7SD, it is very hard to debug if you don’t find any error message. Are you debugging in localhost? Please make sure you’re properly connected to your database.

  3. Hi, Mike. Thank you for the Post. It helped me very much.

    The only problem is that returns an error to me:

    Parse error: syntax error, unexpected ‘:’

    In this line: header(“Content-type: image/png”);

    Could you help me?

  4. Just want to say a big thank-you. I’ve tried a small handful of tutorials on this, and I constantly got a really long string outputted to me. Yours worked perfectly. Thanks again!

  5. How to upload image and add the path to MySQL database not inserting the image itself then display it using php oop pdo? thanks.

  6. Goodpm po ,i tried the code above and do all the changes including the database name, fields but somehow i wasn’t able to display the image , can you help me ? thanks in advance

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to top