Wednesday 23 October 2013

How to Upload Files / Images In Database

Here we are going to see how to upload files or images in database using insert query. It's very easy to insert your images in database, while uploading your image you must enter enctype="multipart/form-data" in the form, otherwise it will not work. Find the steps below:





Code:

<form name="form" method="post" action="" enctype="multipart/form-data">
 <h1>Upload Image</h1>
 <p>File Upload : <input name="file" type="file" value="" /></p> 
 <p><input type="submit" name="submit" value="submit" /></p> 
</form>

insert Query:

<?php 
 include('database.php'); 
 if(isset($_POST['submit'])) 
 { $name=$_FILES['file']['name']; 
 $type=$_FILES['file']['type']; 
 $size=$_FILES['file']['size']; 
 $temp_name=$_FILES['file']['tmp_name']; 
$dir="uploads/.$name"; 
 move_uploaded_file($temp_name,$dir); 
 $insert=mysql_query("insert into upload(name,type,size,location) values('$name','$type','$size','$temp_name')");
 }
 }
 ?> 

if you want to insert a particular type of image in your database, use if condition to check whether this image will satisfy the conditions or not. If it satisfies the condition then the image will be inserted into database otherwise it will shows the error message.

condition to check image: 

if(($type="image/png") || ($type="image/jpeg") || ($type="image/jpg")) 
 {
 $dir="uploads/.$name"; 
 move_uploaded_file($temp_name,$dir); 
 $insert=mysql_query("insert into upload(name,type,size,location)
values('$name','$type','$size','$temp_name')"); 
 }

Database:


Database Name            : image_upload
Database Table Name : upload

Connect file:

<?php 
 $hostname="localhost"; 
 $user="root"; $pwd="";  
$cnt=mysql_connect($hostname,$user,$pwd); 
$select_db=mysql_select_db("image_upload",$cnt); 
?>

No comments:

Post a Comment