Tuesday, June 21, 2011

Save image in database(MySQL & Blob datatype)


Hi,

This is rather interesting topic, but is among the simpler one's. In this I will show how to save an image in its actual format in the database as data and fetching it as an image to the web page. First of all create a database table and assign "blob" data type to the fields that will hold the image. Here is the schema for the database table that I am using:

CREATE TABLE `employees` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`empname` VARCHAR(50) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
`profile_pic` LONGBLOB NULL,
`ext` VARCHAR(5) NULL DEFAULT NULL COLLATE 'latin1_general_ci',
PRIMARY KEY (`id`)
)

[You can find the entire source code here]

Now that my table is ready lets move on to the HTML. It is a pretty simple one just a form with couple of fields as follows:

<form method="post" action="" enctype="multipart/form-data">
Enter Name:<br/><input type="text" name="emp_name" /><br/><br/>
Profile Pic:
<input type="file" name="pic" /><br/><br/>
<input type="submit" value="Save Image" />
</form>

The page looks something like:



After saving the data, this is what I get:


Code and Explanation:

When the form is submitted here is what I have done:


$content=file_get_contents($_FILES['pic']['tmp_name']);
$content=mysql_escape_string($content);

@list(, , $imtype, ) = getimagesize($_FILES['pic']['tmp_name']);

if ($imtype == 3){
$ext="png";
}elseif ($imtype == 2){
$ext="jpeg";
}elseif ($imtype == 1){
$ext="gif";
}


$q="insert into employees set empname='".$_POST['emp_name']."',profile_pic='".$content."',ext='".$ext."'";
mysql_query($q);

This is pretty straight forward code. The main part of this code is:

$content=file_get_contents($_FILES['pic']['tmp_name']);
$content=mysql_escape_string($content);


In this unlike our traditional approach I am not using the copy or move_uploaded_file function to save the image in a files. Rather I am reading the content of the file using file_get_contents(), then I am encapsulating the special characters in that content with mysql_escape_string(), so that it can be inserted in the database table. And last but not the least saving the content in the table.

In the following lines:


@list(, , $imtype, ) = getimagesize($_FILES['pic']['tmp_name']);

if ($imtype == 3){
$ext="png"; 
}elseif ($imtype == 2){
$ext="jpeg";
}elseif ($imtype == 1){
$ext="gif";
}


I am just retrieving the extension of the image and finally store the above content and the extension in the database by:


$q="insert into employees set empname='".$_POST['emp_name']."',profile_pic='".$content."',ext='".$ext."'";
mysql_query($q);

So one part of my job is done. My image is now saved in the database in blob format.

Now I have to fetch the data that is stored and display it in image format. For doing that is the following code:

<table>
<?php
$q="select * from employees";
$resultset=mysql_query($q);
if(mysql_num_rows($resultset)==0){
?>
<tr>
<td width="400">No Images Saved</td>
</tr>
<?php
}
while($rec=mysql_fetch_array($resultset)){
?>
<tr>
<td width="200"><img src="load_image.php?pic_id=<?php echo $rec['id']; ?>"></td>
<td><?php echo $rec['empname']; ?></td>
</tr>
<?php
}

?>
</table>

This again is pretty simple to understand. I am fetching all the records and displaying them in the grid format. The most important part here is the line:

<img src="load_image.php?pic_id=<?php echo $rec['id']; ?>">

here to load the image I am passing the record id to another page, load_image.php. This page will convert the data into image. In load_image.php I have:


$q="select * from employees where id=".$_GET['pic_id'];
$rec=mysql_fetch_array(mysql_query($q));
$data=$rec['profile_pic'];
header('Content-Length: '.strlen($data));
header("Content-type: image/".$rec['ext']);
echo $data;

First three lines are pretty straight forward. I am fetching one particular record from the table based on the ID supplied in the get parameter as was earlier given in <img src="load_image.php?pic_id=<?php echo $rec['id']; ?>">.

Next I am setting the content type and content length that is to be returned. The content type is the extension or rather file type that I was storing earlier, and content length is simply the length of the content in bytes. And finally to return the data in image format I give "echo $data;" to wrap things up.

Hope this helped. Download: blob.zip





21 comments:

  1. Wow! This is Great. Thanks!
    But Is there any possibilities to make the Database heavier for such method?
    Please suggest Hasan Da Which one is better between using Blob type image saving in Database and the traditional copy or move_uploaded_file method.

    ReplyDelete
  2. Traditional one is better ofcourse. This should be used only if it is required, depends on the situation.

    ReplyDelete
  3. Fantastic post. Here’s a tool that lets your build your online database without programming. There is no need to hand code PHP. Cut your development time by 90%
    http://www.caspio.com/

    ReplyDelete
  4. nice buddy..........
    thanx.......



    From : jish pansniya....

    ReplyDelete
  5. nice........ yr.

    thanx....

    from : jish pansniya

    ReplyDelete
  6. Nice tutorial dude.

    THanks a lot.

    from: roca

    ReplyDelete
  7. Nice . I'll try this one, i'm getting hard to look for some code how to retrieve image from database. Thanks dude!

    ReplyDelete
  8. when i try ur file in my server, its cannot load the images. is there any file that i have to listed in php.ini or else before i use that script ?

    ReplyDelete
    Replies
    1. No. There are no extra dependencies for this code. Check for any error messages returned.

      Delete
  9. thank's dude it's working

    ReplyDelete
  10. if am using mysql database to store image in db, what kind of data type i have to use..

    ReplyDelete
  11. Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\blob\example.php on line 43

    Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\blob\example.php on line 50

    ReplyDelete
    Replies
    1. Please check your database configuration, SQL query etc.

      Delete
    2. go to load_image.php and 3rd line and change the database name suppose my database name is pos....mysql_select_db("pos");

      Delete
  12. Help! It does not show the image in the Saved Images part.
    I just made the database exactly like yours and copied your code as it is.

    ReplyDelete
  13. Hi there - wow it works! I had been looking everywhere online to find some tips on the best way to handle blobs and this is the one!

    Many thanks for sharing it with us.

    ReplyDelete
  14. owa ....such a nice tutorial..why so..!! it is already done..
    but 1 issue how to update a particular picture ?
    any code you..help

    Thanks in Advance

    ReplyDelete
  15. Nice tutorial. I stumbled on your site from Google. My expectation was met after going through your tutorial. I am going to implement it right away .

    ReplyDelete
  16. Terimakasih banyak..~
    Thanks for tutorial.. very helpful :)

    ReplyDelete