Translate

Saturday 27 September 2014

Upload CSV file to Database using PHP

Explaination:

  1.We have connect to datadase.Then cretae  the table what are the fields is in the csv file
that names only we have to put into field name.

2.We have to check the condition for to upload CSV file to database.

3. $min = strtotime('2014-02-02');
$max = strtotime('2014-08-02');
$val = mt_rand($min, $max);
$string= date('Y-m-d H:i:s', $val);
The above Coding is used to display random date.

4.THen we will use For loop ahat are the datas in DB that has to been uploaded.

5.If there is any unexpected  string function in CSV file is not be uploaded so we will use
 str_replace(); function.
 $emapDatass[$i] = str_replace('"','',str_replace("'", "", $emapDatass[$i]));

6. If there is any ID means suppose in DB id is only one digit and you want to generate it has an 
   8digit means use str_pad();function.
   $VendorID = str_pad($emapDatass[1], 8, "0", STR_PAD_LEFT);

7. While inserting the data Just you put this variable where You want.  
   $sql = "insert into Tbl_name (`VendorName`,`VendorID`, `HotelClass`, `) 
    values('$emapDatass[0]','$VendorID','$emapDatass[2]',......)";          

Form:

 <form action="" method="post" enctype="multipart/form-data">
        <label for="file">Filename:</label>
        <input type="file" name="file" id="file"><br>
        <input type="submit" name="submit" value="Submit">
    </form>

PHP Coding:


<?php
include('db.php');
if(isset($_POST['submit']))
{
$fname = $_FILES['file']['name'];     
$chk_ext = explode(".",$fname); 
$filename = $_FILES['file']['tmp_name'];   
if($_FILES["file"]["size"] > 0)
{
if($chk_ext[1]=='xls' || $chk_ext[1]=='csv'  )//Check the Condition whether CSV or XLS file
{
$file = fopen($filename, "r");
$tot = 0;  
while (($emapDatass = fgetcsv($file, 10000, ",")) !== FALSE)
{
// Convert to timetamps
$min = strtotime('2014-02-02');
$max = strtotime('2014-08-02');
// Generate random number using above bounds
$val = mt_rand($min, $max);
// Convert back to desired date format
$string= date('Y-m-d H:i:s', $val);
if($tot!="0")
{
for($i=1;$i<=11;$i++) {
$emapDatass[$i] = str_replace('"','',str_replace("'", "", $emapDatass[$i]));
}
$VendorID = str_pad($emapDatass[1], 8, "0", STR_PAD_LEFT);
$sql =  $sql = "insert into Tbl_name (`VendorName`,`VendorID`, `HotelClass`,field_names.......) 
values('$emapDatass[0]','$VendorID','$emapDatass[2]','$emapDatass[3]',......)"; 
$result = mysql_query($sql);    
}
if(!$result)
{
$msg="Invalid File:Please Upload CSV File!!";
}
$tot++;
}
}
else
{
echo "<script>alert('Please check your flie extension');</script>"; 
echo "<script>window.location='upload_overview.php';</script>";

}
}
fclose($file);
$msg="CSV File has been successfully Imported!!";
}   
?>

No comments:

Post a Comment