Saturday, October 6, 2007

Image Uploading and Retreving in Mysql

Uploading and Retrieving Images from Mysql

I wrote this tutorial for the freshers who learn uploading and retrieving images from mysql database. Here i am creating 3 scripts one for uploading and retrieve.

Our database name is "test" and table name is "image". To make the progarm simple we have only 2 fields id and image. image is a BLOB. lets go inside the script..

Upload.php:


if(isset($_POST['submit']))
{

//connecting to mysql and database
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('test');

//verification.........
$image_name=$_FILES['image']['name'];
$image_servername=$_FILES['image']['tmp_name'];
$image_type=$_FILES['image']['type'];
$image_size=$_FILES['image']['size'];

//uploading into the server..once you read it you can delete it.........
$upfile=$_FILES['image']['name'];
$move=move_uploaded_file($_FILES['image']['tmp_name'],$upfile);

//verifing your uploading........
if($move)
{
echo 'UPloaded successfully';
}
else
{
echo 'problem in uploading';
}


//reading the contents of the image from server...
$fp=fopen($upfile,'r');
$contents=fread($fp,filesize($upfile));

//adding slashes
$contents=addslashes($contents);

//inserting into mysql database...
$sql="insert into image(image)values('$contents')";
$result=mysql_query($sql);
if($result)
{
echo 'Inserted into database';
}
else
{
echo "mysql_error()";
}

}
else
{
?>

//our form to upload the data.

so you have to create your form here......
}
?>

Retrieve.php

Now a simple script fetch the image from the database.


// mysql connection
mysql_connect('localhost','root','');
mysql_select_db('test');

//retrieving data from mysql
$sql="select * from image";
$result=mysql_query($sql);


while($row=mysql_fetch_assoc($result))
{
//extracting the id from result set.
$id=$row['id'];

// in single script we cannot send more than one header.
echo "img src=\"retrieve1.php?id=$id\" ";
}
?>

and the final one.

Retrieve1.php

// this is to send the header for each request.


// mysql and database connection
mysql_connect('localhost','root','') or die(mysql_error());
mysql_select_db('test');

// retrieving result set
$sql="select * from image where id = $id";
$result=mysql_query($sql);
$row=mysql_fetch_assoc($result);

//fetch the image from result set
$image=$row['image'];

//send the header
header("Content-type:image/jpeg");

//print the image..
print $image;
?>


Kindly send me your critics..........