Upload and store an image in the Database with PHP

Uploading and storing an image in a database using PHP is a common task in web development. By storing images directly in the database, you can easily manage, retrieve, and manipulate image data alongside other relevant information. This simplifies data backup and recovery processes and ensures data integrity.

In this article, I will show you 3 approaches to accomplish this –
1. Storing image files by saving their file path or name,
2. Encoding images as base64, and
3. Storing images as BLOB (Binary Large Object) data.

Additionally, we will delve into the retrieval process to display the uploaded images from the database.

By the end of this article, you will have a better understanding of various techniques to upload images to a database and retrieve them for display on your web application.

Upload and store an image in the Database with PHP


Table of Content

  1. Create a Table to store the image
  2. Database Configuration
  3. Save file path or name
  4. Storing image as base64_encode()
  5. Storing image as BLOB (Binary Large Object) data
  6. Conclusion

1. Create a Table to store the image

In the example, I am using images table for storing data.

  • name – This field is used to store the image file name.
  • image – This field is used to store the image base64 generated value.
  • imagetype – Store image file type – jpeg, jpg, png, gif
  • image_blob – Store file in Blob format.
CREATE TABLE `images` (
    `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    `name` varchar(200) DEFAULT NULL,
    `image` longtext,
    `imagetype` varchar(20) DEFAULT NULL,
    `image_blob` longblob
);

2. Database Configuration

Create a config.php file for database configuration.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}

3. Save file path or name

You can either save the full path or name of an image in your MySQL database table. Retrieve the image name or path from the MySQL database and use it to make an image source.

Here, I am storing the file name in the MySQL database.

<?php
include("config.php");

if(isset($_POST['but_upload'])){
 
    $name = $_FILES['file']['name'];
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    // Select file type
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Valid file extensions
    $extensions_arr = array("jpg","jpeg","png","gif");

    // Check extension
    if( in_array($imageFileType,$extensions_arr) ){
         // Upload file
         if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
              // Insert record
              $query = "insert into images(name) values('".$name."')";
              mysqli_query($con,$query);
         }

    }
 
}
?>

<form method="post" action="" enctype='multipart/form-data'>
  <input type='file' name='file' />
  <input type='submit' value='Save name' name='but_upload'>
</form>

Retrieve file by name

Select the name or path of the image which you have stored in the database table and use it in the image source.

Example

<?php

$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

$image = $row['name'];
$image_src = "upload/".$image;

?>
<img src='<?php echo $image_src;  ?>' >

4. Storing image as base64_encode()

You can store the full image in the Database table by converting it into the base64 format. You don’t need to store image reference in the Database table e.g. name, path, and not require to store the image on your server.

In PHP base64_encode() method is been used for base64 conversion. Before storing it in the database I append data:image/'.$imageFileType.';base64, text with base64 value.

Now when you need to display the image just fetch the value and use it as an image source.

Note – In the example, I upload the image file to a folder. You can remove the upload code if you only want the image will accessible through base64 stored values in the database.

<?php
include("config.php");

if(isset($_POST['but_upload'])){
 
    $name = $_FILES['file']['name'];
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    // Select file type
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Valid file extensions
    $extensions_arr = array("jpg","jpeg","png","gif");

    // Check extension
    if( in_array($imageFileType,$extensions_arr) ){
         // Upload file
         if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){
               // Convert to base64 
               $image_base64 = base64_encode(file_get_contents($target_file) );
               $image = 'data:image/'.$imageFileType.';base64,'.$image_base64;

               // Insert record
               $query = "insert into images(image) values('".$image."')";
               mysqli_query($con,$query);
         }
    
    }
 
}
?>

<form method="post" action="" enctype='multipart/form-data'>
    <input type='file' name='file' />
    <input type='submit' value='Save name' name='but_upload'>
</form>

Display image stored as base64 in the database

Select the stored base64 value and use it in the image source.

Example

<?php

$sql = "select image from images order by id desc limit 1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

$image_src = $row['image'];
 
?>
<img src='<?php echo $image_src; ?>' >

5. Storing image as BLOB (Binary Large Object) data

Storing images as BLOB data involves saving the binary image representation directly in a database column. It simplifies image management but can increase database size and impact retrieval speed. Consider factors like image volume and performance before choosing this method.

In the below example, when file is uploaded successfully then reads the contents of the uploaded file using file_get_contents() and encodes it in base64 format using base64_encode().

Insert the file’s extension (imagetype) and base64-encoded image data (image_blob) into the images table.

<?php
include("config.php");
if(isset($_POST['but_upload'])){

    $name = $_FILES['file']['name'];
    $target_dir = "upload/";
    $target_file = $target_dir . basename($_FILES["file"]["name"]);

    // Select file type
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

    // Valid file extensions
    $extensions_arr = array("jpg","jpeg","png","gif");

    // Check extension
    if( in_array($imageFileType,$extensions_arr) ){

        // Upload file
        if(move_uploaded_file($_FILES['file']['tmp_name'],$target_file)){

            // Convert to base64 
            $image_base64 = base64_encode(file_get_contents($target_file));

            // Insert record
            $query = "insert into images(imagetype,image_blob) values('".$imageFileType."','".$image_base64."')";

            mysqli_query($con,$query);

        }

    }

}
?>

<form method="post" action="" enctype='multipart/form-data'>
    <input type='file' name='file' />
    <input type='submit' value='Save name' name='but_upload'>
</form>

Display image stored as BLOB in the database

Read imagetype,image_blob field values. In the <img > tag src attribute set data URI, which includes the image type retrieved from the database ($imagetype), followed by the base64-encoded image data ($image_src).

<?php

$sql = "select imagetype,image_blob from images order by id desc limit 1";

$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);

$imagetype = $row['imagetype'];
$image_src = $row['image_blob'];

?>

<img src='data:image/<?= $imagetype ?>;base64,<?= $image_src ?>' >

6. Conclusion

We have explored three approaches for uploading and storing images to database using PHP. Each method has its own advantages and considerations. By centralizing data management, ensuring data integrity, and simplifying backup processes, storing images in the database offers benefits.

However, factors such as image volume and performance should be considered. Armed with this knowledge, you can now make informed decisions when handling image data in PHP for your web applications.

You can also view this tutorial if you want to know how you can store a video file in the MySQL database.

If you found this tutorial helpful then don't forget to share.

87 thoughts on “Upload and store an image in the Database with PHP”

  1. It really helped me, thank you!

    Just for further reference, it would be better check if the image already exists before to post another one, here a simple solution with an OOP approach:

    $result = $conn->query(“select * from images where name=’$name'”);
    if( !$result->num_rows ) $conn->query(“insert into images(name) values(‘”.$name.”‘)”);

    Reply
  2. Hi,
    I am able to upload images succesfully .
    but unable to retrieve..its just shows a blank broken image icon..please help me out ..

    And than you sooo much for the post..

    Reply
  3. Works for me uploading an mp3 file. What about appending a date and time to the file name to prevent overwriting? Or another method?

    Reply
  4. Hi Mr. Yogesh ,
    I am new to php . I am trying to fetch the image stored in database by using procedural mysqli. I am not able to fetch the image. Instead of image some code is showing there. Can somebody please help me out with this error…? Any help is appreciate

    Reply
  5. Hi Mr. Yogesh ,
    As u said earlier, instead of storing an image in MySQL database, it’s better to store in the server and save the reference in the database table to keep track of the location..would u please teach me how to do it..

    Reply
  6. Hello there this is my first time to come here . You are really creating a quality code here. But I’m suffering in very common but problem in PHP. I have a website for different user’s portfolio. Now what I’m saying is if a single user upload images to their portfolio so if any one will check their portfolio just that user’s images will appear on that user portfolio page.

    Reply
  7. Hello could you please explain to me why the name in php code is just ‘upload’ but not ‘but_upload’ meanwhile in your input form the name is ‘but_upload’.
    if(isset($_POST[‘upload’])){

    Thank you.

    Reply
  8. Hi, thank you very much for uploading demo and codes, works perfectly well. However Retrieve code prints only first record, please advise how can I get full list of all of uploaded images,
    Saj

    Reply
  9. I’m trying to upload the path to a locally created database using phpmyadmin. The php file doesn’t show any errors, but the name won’t go to the database.

    Reply
    • Thanks for the help. Through talking in the mail I found out that I set my database fields to not null so it couldn’t insert the reference. Also my upload path was outside of htdocs. Once again thanks for the help.

      Reply
  10. Hi! Sir I am new to PHP. How can i store regno, name, photo in mysql table, and also view the records. i have done except image. please send me code thanking you

    Reply
  11. My image is not displayed. I have tried you way. It has not uploaded. While uploading images, name of image must upload or pathname of image. Which one is better?

    Reply
  12. Please help, it say, Notice: Undefined index: file for $name = $_FILES[‘file’][‘name’];
    and the same thing for $target_file = $target_dir . basename($_FILES[“file”][“name”]);

    It say that the name “file” is undefined.

    Reply
  13. hello i got a few problem.. i want to upload by image into the system but i also want its name to change automatically into its id that im already set on the database..

    Reply
  14. “MySQL server has gone away”
    I am getting this message after uploading the image and it is not uploading in database.

    Reply
  15. Hi, thanks for your code. But I am facing some problem. The image is uploaded to the intended folder but its name is not being inserted into the database. What might be the possible cause and solution?

    Reply
  16. Hi,

    I’m trying to use prepared statement (procedural). However, I need to replace the ? with ‘”.$image.”‘, but this would normally be $image. Why is $image wrapped in ‘””‘ and do you know how to resolve this?

    Thanks a million!
    Carl

    Reply
    • Sorry, I want to rephrase my question. How can I retrieve one image at a time? I don’t want to retrieve all images I have uploaded.

      Reply
  17. am very new to php and i created a php script and created a database with phpmyadmin but my search form is displaying all the records in my database without any one actually searching for a particular content or info in my database how to solve this please….

    Reply
  18. I can successfully insert multiple image file selected at once to database.But, what if a user uploads multiple images one after another(eg: clicked on choose file and uploaded one picture, then again choose on file and selected 2nd picture. Now I have 2 pictures), how to insert both images to database.? as in my case, only latest picture is getting inserted.

    Reply
  19. I can`t view my images in the table that i store in the upload file i use this code
    }
    $sql=”SELECT * FROM images”;
    $result=$con-> query($sql);
    if ($result-> num_rows >0){

    while ($row =$result-> fetch_assoc()){
    $image_src2 = $row[‘image’];

    echo “”;

    echo “<img src='’/>”;
    echo “”.$row[‘prod_code’].””;
    echo “”.$row[‘prod_name’].””;
    echo “”.$row[‘prod_price’].””;
    echo “”;
    echo “”;
    }

    };

    Reply
  20. hello,
    i managed to get the filename & image uploaded to database & server by following your example.
    but how to insert the filename & image file to database & server if i have 3 input type file in one form? the example show single input type file ony.
    appreciate your help.
    thank you.

    Reply
  21. if(move_uploaded_file($_FILES[‘file’][‘tmp_name’],’upload/’.$name)){
    i am not able to move the image
    this if condition is not working

    Reply

Leave a Comment