How To Display Image from Database in PHP?

[adinserter block=”34″]

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.

[purchase_link id=”16411″ text=”Download Now” style=”button” color=”green”]

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


Comments

23 responses to “How To Display Image from Database in PHP?”

  1. Ian sinel Avatar
    Ian sinel

    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

  2. Any error messages?

  3. Syrine Ayari Avatar
    Syrine Ayari

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

  4. Benjamin Coelho Avatar
    Benjamin Coelho

    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!

    1. You’re welcome @benjamincoelho, glad this source code helped you!

  5. Filipe Soares Avatar
    Filipe Soares

    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?

    1. Hello @disqus_BLZDyyl6kE, you’re welcome! About the error you reported, it looks like you mistyped “:”, it must be “;”

  6. Hi Mike,I tried this code above but my image can not display,however there wasnt any error

  7. 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.

  8. Unmesh Pt Avatar
    Unmesh Pt

    how can i get one more images from database

    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.

  9. Hi @unmeshpt , you should learn how to query from the database to retrieve multiple records with your images. Our step by step tutorial here should help you, see: https://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  10. Parth Decisive Fitness Avatar
    Parth Decisive Fitness

    it doesn’t display image so what can i do for that

    1. Hi @parthdecisivefitness , what was the error message you encounter?

  11. James Frame Avatar
    James Frame

    This was very helpful

    1. Thanks for the feedback @James! I’m glad to help you!

  12. Hi @beneciofernandes, I’m glad our tutorial was very helpful to you. You can do the same with text data by following our tutorial here: https://www.codeofaninja.com/2011/12/php-and-mysql-crud-tutorial.html

  13. Hi @anivicks, thanks for the kind words. You’re welcome!

  14. Hi @anivicks, unfortunately, we do not support MySQLi.

  15. Iulia Maria Rus Avatar
    Iulia Maria Rus

    Hello! What did I do wrong if it says that the method bindParam is not recognized? Thanks 🙂

  16. well how do i upload a pic???????

  17. tylerjusfly Avatar
    tylerjusfly

    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?

Leave a Reply

Your email address will not be published. Required fields are marked *