Insert and Retrieve file with MySQL

Some of you might be knowing that there is a functionality in MySQL database for storing files and retrieving the same.

This is mainly used when we need to reduce response time for retrieving and using files in our application.

I am listing here the method for inserting image file in and retrieving image file from MySQL database using PHP.

1) For inserting data into MySQL you need to convert the image file into binary format, this is accomplished by using ‘BLOB’ datatype in MySQL. Basically there are four datatypes TINYBLOB,MEDIUMBLOB,BLOB and LONGBLOB which differs by their storing capacity for characters. For further reference please visit this site MySQL.

2) Create a column having datatype from any of the above described datatypes.

3) Suppose name of the column is ‘image’ and table name is ‘uploadtest’.


// make connection with database
$connection = mysql_connect("hostname", "dbusername", "dbpassword") or die ("Unable to connect!");
mysql_select_db("dbname") or die ("Unable to select database!");

$qry = "INSERT INTO `uploadtest`(`image`) VALUES(LOAD_FILE('/var/www/html/urfolder/abc.jpg'))"; // where "/var/www/html/urfolder/abc.jpg" is the full physical path of the image.

mysql_query($qry) or die (mysql_error());


4) Now for displaying image in the browser you need to execute following code


$selqry = "SELECT `image` FROM `uploadtest`";
$selrs = mysql_query($selqry);
header('Content-type: image/jpeg '); //set header with content type 'jpeg' for displaying image
while ($row = mysql_fetch_assoc($selrs))
    echo $row['image'];    

5) Note you can upload and retrieve any type of file.

6 Responses to “Insert and Retrieve file with MySQL”

  1. Faisal says:

    thanks for info

  2. harshal says:

    i have store it in a folder now i want to retrive it how to do that..

  3. Javier says:

    I was wondering why you don’t upload the files into a folder and then you save the path of name of file.

  4. Violet Edick says:

    Wow, I didn’t knew this, thanks.

Leave a Reply