Store Images in MySQL Database with PHP

For any web application uploading an image is comman task. But what is the comman way to manage the uploaded files?

Generally what we do is place the uploaded file on specific folder and store the name of the image or some times path to image in VARCHAR field of the database table.

But this article is to cover the concept to store the image in mysql database. Later on we will discuss how to show the stored image from database to the web page.

For this article I am assuming that you are somewhat familiar with the PHP basic file upload process. So without explaining that process I will directly go with the main part of this article.

I will directly show you the code which insert the image into MySQL database. But before moving to that code let me explain the datatype which we are going to use for the image. We will use BLOB datatype of MySQL.

BLOB in MySQL

BLOB stands for Binary Large Object. This types used to store the Large Binary Objects. We can have 4 type of this Datatype.

  1. TINYBLOB
  2. BLOB
  3. MEDIUMBLOB
  4. LONGBLOB

Store Image in MySQL Database

Now considering you have pressed the upload button for the image and you are at code block at which you want to save image in the database table. Have a look at the code block for the same.

// Check if we have file uploaded or not. if(is_uploaded_file($_FILES["to_upload"]["tmp_name"])) { // Instead of moving file to any specific location // We will read the binary content of the uploaded image $image_content = file_get_contents($_FILES["to_upload"]["tmp_name"]); $image_content = base64_encode($image_content); // $image_content can be stored in the MySQL table with BLOB datatype }
  // Check if we have file uploaded or not.
if(is_uploaded_file($_FILES["to_upload"]["tmp_name"]))
{
// Instead of moving file to any specific location
// We will read the binary content of the uploaded image
   
$image_content = file_get_contents($_FILES["to_upload"]["tmp_name"]);
$image_content = base64_encode($image_content);
   
// $image_content can be stored in the MySQL table with BLOB datatype
}

This $image_content variable can be stored in MySQL table in the fields with datatype BLOB. In next post we will see how to show this stored binary data as an image in webpage.

Subscribe to RSS Feed to keep updated with the new upcoming posts.

Related Posts

Written by Avinash

Avinash Zala is leading various projects which deals with the various technology involved with the web. A combination of perfect technical and management skills. Avinash would like to chat with you and convert your imagination into the working system. You can get in touch with him on Facebook and Twitter.

View all posts by: