Showing posts with label Database. Show all posts
Showing posts with label Database. Show all posts

Sunday, December 5, 2010

File Uploading, Storing Pictures in MySQL through PHP, and retrieving the Pics.

In this Blog I am endeavoring to provide the basics of file uploading in PHP, storing and retrieving Blobs in MySql through PHP . 


First of all lets create a table in MySQL. Here is the Code :-


 create database Hypatia; 
use Hypatia;
create table Pictures(PictureNo int primary key AUTO_INCREMENT,Picture blob);







The PictureNo column is an auto increment field, this will help us in identifying the newly entered picture.

Create a page having a HTML form with a file control. This form must use the post method, and must have it's encoding type set to multipart/form-data.
Here is the page with the form:-
PicUpload.html

<form id="picform" method="POST" action="PicUpload.php" encType="multipart/form-data">
Select a Picture<input type="file" name="f1" />
<input type="submit"/>

</form>


The File Uploader.
This file receives the uploaded picture from the previous form. The uploaded picture is automatically uploaded to the server and it's path can be accessed through the $_FILES['f1']['tmp_name']; construct where f1 is the name of the file control.$dest=$_FILES['f1']['name']; is the name of the file on the Client. We will copy it using the same name. The move_uploaded_file($src,$dest); copies the file from the source to destination. All files are being stored in the uploads directory. The rest is more or less self explanatory. Any queries are invited.
PicUpload.php 

<?php
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$src=$_FILES['f1']['tmp_name'];
print("The file has been uploaded with the temporary name = $src<br/>");
$dest=$_FILES['f1']['name'];
print("The file had the original name  = $dest<br/>");
$destpath="uploads/$dest";
$result=move_uploaded_file($src,$destpath);
if($result)
{
print("File Copied<br/>");
print("The copied Picture <img src='$destpath' width='200px' height='200px'/>");
$imagesize=filesize($destpath);
$pic=addslashes(fread(fopen($destpath,"r"),$imagesize));
$queryresult=mysql_query("insert into Pictures values(0,'$pic')");
$NewPicNo=mysql_insert_id();
print("<br/>Picture Inserted successfully");
print("<br/>The Picture from the Database <img src='ShowPic.php?picno=$NewPicNo' width='200px' height='200px'/>");
}
else
print("File not Copied");

?>


The file that retrieves the Picture from the database.




ShowPic.php

<?php
$url="localhost";
$username="root";
$password="";
$link=mysql_connect($url,$username,$password);
mysql_select_db("Hypatia");
$picno=$_GET['picno'];
$access=mysql_query("select picture from pictures where pictureno=$picno");
$row=mysql_fetch_row($access);
Header("Content-type:image/jpg");
echo $row[0];
?>