How to store image in MySQL database with PHP

 

If you are a newbie PHP developer, you will not easily get the idea of storing images in database, but the answer is very simple, You are not going to store the actual image in the database but the image name which is actually uploaded in a folder.

There are two methods you can follow to store an image into the MySQL database,

1. Uploading images in a folder and storing the reference in the database (usually the image name with extension)
2. Converting images into binaries and storing the binaries in database using a special data type called BLOB.

First method is often used by almost all of the website developers and it is the best way. The main reason is images are uploaded in the folder, If you want to optimize all the uploaded images in future, you can easily download the images from server and do the optimization and upload it back.

But in the second case, it is pretty difficult, you have to update each and every record in the database and also your database size will become very large and cannot be easily downloaded.

So, In this example we are going to do the First method which is uploading the images in a folder and storing the reference into the MySQL database.

Lets start the coding part:

1. In this example I have used mysqli instead of mysql, because mysql will be deprecated soon.
2. Also, I have used OOPS concept to upload and retrieve images from MySQL database to keep the code clean and neat.

So, lets begin with the upload class (upload_class.php):

The code is self explanatory, just read the comments in the class to understand.

Basically this upload class has four functions,

1. __construct() is a PHP magic function, this function will be called automatically by PHP when you create an object from your class. In the program I’m using __construct() to connect to the MySQL database.

2. upload_image_and_store() is to validate the file and also to upload the image in a folder.

3. store_image_in_db() is to store the image reference (name) into the MySQL table.

4. get_images() is to retrieve the image list from database table.

 

Here is the usage of the above class:

1. Upload image form (index.php):

If you see the above code, the PHP part is very minimal because of the Object Oriented methodology.

Here is the SQL Dump for the table ‘image_uploads

 

2. Retrieve image from database (list_images.php):

In this file, I’m reading the image names from the table ‘image_uploads‘ and showing a preview by pointing it to the appropriate image folder (uploads/).
For your convenience, I have also given a demo and download of this script here, enjoy:

demo download

 

5 Comments

Add a Comment

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