Thursday, March 19, 2009

Saving images in MySQL with PHP

Here is the small code to save the image in MySQL with the help of PHP.
Images are saved in MySQL as BINARY data. BINARY data can not be saved in varchar or char data types, for this purpose we need a data type which can handle binary data. BLOB columns are treated as binary strings (byte strings). The following table is fulfilling our requirements for a simple test with a BLOB field.


CREATE TABLE `images` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`image` BLOB NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

Now we have a MySQL table ready to store the image. Next steps are easy i.e.



  1. Read the image

  2. Encode the image data

  3. Save binary data in DB


These 3 steps are performed with the following PHP code


$image = chunk_split(base64_encode(file_get_contents("image.jpg")));
$query = "INSERT INTO images (image) VALUES('$image')";
mysql_query($query) or die(mysql_error());
echo "Image id is ".mysql_insert_id();

Now we have saved the image in database successfully. The next step is to display the image.


// showimage.php
header('Content-type: image/jpeg');
$query = "SELECT image from images where id=1";
$rs = mysql_fetch_array(mysql_query($query));
echo base64_decode($rs["image"]);


Now to display this image



img src="showimage.php" />





I have copied this valuable code from my friend's blog

( where he had answered many user queries in reqponse for this posting.

http://www.einfobuzz.com/2010/04/saving-images-in-mysql-with-php.html

 
 
 

No comments: