Saturday, January 5, 2013

Image Uploading in PHP


In this article I will explain how to upload an image into a database and how to see the uploaded image in in the front end. To do this first we create a database and table.
Create Database
  
$con=mysql_connect (
"localhost","root","");if(!$con)
{
 
die('Could not connect'.mysql_error());}if(mysql_query ("create database ABC",$con))
{
 
echo "Your Database Created";
}
else{
 
echo "Error".mysql_error();}
mysql_close($con);
?>
Create Table
$con = mysql_connect ("localhost","root","");if (!$con)
  {
 
die ('Could not connect: ' . mysql_error());
  }
mysql_select_db (
"ABC", $con);
$sql =
"CREATE TABLE tbl_image
(
`id` INT( 50 ) NOT NULL AUTO_INCREMENT ,
`photo` VARCHAR( 50 ) NOT NULL ,
`status` INT( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
)"
;
mysql_query($sql,$con);
mysql_close($con);
?>
When you create a database and table using MySql you will write the code for uploading an image. The code for uploading an image is as follows:
Upload an Image

$con=mysql_connect(
"localhost","root","");
mysql_select_db (
"ABC",$con);if(@$_POST ['submit'])
{
$file = $_FILES [
'file'];
$name1 = $file [
'name'];
$type = $file [
'type'];
$size = $file [
'size'];
$tmppath = $file [
'tmp_name']; if($name1!="")
{
if(move_uploaded_file ($tmppath, 'image/'.$name1))//image is a folder in which you will save image
{
$query=
"insert into tbl_image set photo='$name1'";
mysql_query ($query) or
die ('could not updated:'.mysql_error());echo "Your image upload successfully !!";
}
}
}
?><html ><head>
<
title>Image Upload</title>
</
head>
<
body bgcolor="pink"><form name="form" action="" method="post" enctype="multipart/form-data">Photo <input type="file" name="file" /><input type="submit" name="submit" value="submit" /> </form>
</
body></html>

Output
When you browse the above code then you will get the following output:
1st.jpg
Now you will click on the Browse button for selecting an image.
2nd.jpg
After selecting an image you will click on the submit button. Then you will get a message i.e. "Your image upload successfully".
3rd.jpg
If you want to see the uploaded an image in the front end then you will write the following code:
Show an Image
  
$con=mysql_connect (
"localhost","root","");
mysql_select_db(
"abc",$con);
@$sql=
"select * from tbl_image where id='1' and status='0'";
@$query=mysql_query($sql);
while(@$row=mysql_fetch_array($query))
{
 @$image=$row [
'photo'];
 
?><img src="image/ echo $image; ?>" width="360" height="150">}?>

Output
When you browse your code you will get the following output:
4th.jpg
Conclusion
So in this article you saw how to upload an image and how to see the uploaded image in the front end. Using this article one can easily understand the concept of image uploading using PHP.

No comments:

Post a Comment