Insert image into MYSQL Table using SQL Statement

chandru rajendran picture chandru rajendran · Jul 20, 2018 · Viewed 7.5k times · Source

I need to insert images in MYSQL database table. The images are stored in the local disk. I am using LOAD_FILE() for inserting the images, but it only stores the path not the image.

If it is not possible to insert from local disk means from where can I get the images? Please give me a solution with what are the resources I need to store my images into the database.

Answer

Godlove Damian picture Godlove Damian · Jul 20, 2018

I'm not sure what your app does, but I strongly advise against storing an image directly to a MYSQL database, in a long run your database will be laggy.

To answer your question, you need to do the following:-

Step 1: Create MySQL Table

Do create a mysql table with a blob type field in it, to save your image.

In our table we have only two fields:

1) image_id of int type

2) image of blob type

Here is the query to create table:

CREATE TABLE pictures ( image_id int(10) NOT NULL auto_increment, image blob, PRIMARY KEY (image_id) );

Step 2: insert image into table

Now we can insert the image into table using the insert into sql. Following is the example of sql:

INSERT INTO pictures VALUES(1, LOAD_FILE('d:\flower.gif'));

We have used the LOAD_FILE() function of MySQL to insert the image data into database.

After inserting the data you can view it using the MySQL tool.

Hope that solves your problem :).