Tuesday 1 January 2013

Insert data in to table from excel file in php


Step -1 :

Open excel file and save as "TAB DELIMITED" text file.
in below sample code, "example.txt" is tab-delimited excel file.

Step -2 : 

Now, follow the below instruction for create code for insert data into table in mysql using php.


<?php

include 'config.php';
// Connect to your database

$fp = fopen("example.txt", "r");    // Open the file('Tab Delimited') for reading

while($line = fgets($fp))      // Loop through each line
{
 
     list ($name, $first) = explode("\t", $line);

     // Split the line by the tab delimiter and store it in our list...

     $sql = "insert into user (name,phone) values ('$name', '$first')";

     // Generate sql string...

     mysql_query($sql) or die ( mysql_error() );        // Execute the sql

}

?>

Download/get data into excel file using php



<?php
//your code for to create your sql statement, we'll call it $query...

 $query="SELECT `candidate_id`, `fullname`,`email`,`alternate_email`, `location`, `mobile`, `landline`, `expyear`, `expmonth`, `keyskill`, `headlineprofile`, `currcmp`, `fuctionalarea`, `basicedu`, `masteredu`, `docedu`, `create_date`, `current_salary`, `current_industry`, `date_of_birth`, `gender`, `marital_status`, `address`,  `city`, `country`, `pincode`,`specialization`, `university`, `edu_year`, `role` FROM `candidate_reg`";


//get the data that we need...

$Result=mysql_query($query);


//fetching each row as an array and placing it into a holder array ($aData)

while($row = mysql_fetch_assoc($Result)){
 $aData[] = $row;
}


//feed the final array to our formatting function...

$contents = getExcelData($aData);

$filename = "myExcelFile.xls";


//code for Save/Open dialog box...

header ("Content-type: application/octet-stream");
header ("Content-Disposition: attachment; filename=".$filename);


//setting the cache expiration to 30 seconds ahead of current time. an IE 8 issue when opening the data directly in the browser without first saving it to a file

$expiredate = time() + 30;
$expireheader = "Expires: ".gmdate("D, d M Y G:i:s",$expiredate)." GMT";
header ($expireheader);


//final output in contents

echo $contents;
exit;
?>

<?php
 function getExcelData($data){
    $retval = "";
    if (is_array($data)  && !empty($data))
    {
     $row = 0;
     foreach(array_values($data) as $_data){
      if (is_array($_data) && !empty($_data))
      {
          if ($row == 0)
          {
              // write the column headers
              $retval = implode("\t",array_keys($_data));
              $retval .= "\n";
          }
           //create a line of values for this row...
              $retval .= implode("\t",array_values($_data));
              $retval .= "\n";
              //increment the row so we don't create headers all over again
              $row++;
       }
     }
    }
  return $retval;
 }
?>