a digital blog

PHP, Tutorial

CSV Export Import with PHP and MySql

CSV Export Import with PHP and MySql

This post explains you about how Export and Import CSV file with MySql. First of all you should know the basic about how to upload a file and how form validation works, to know more about this topic you can read my previous post

So I am leaving the files upload and validations process and directly jumped into CSV Export Import section.

 

Download Link

 

CSV IMPORT into MySql Database with PHP

First of all we should upload csv file into define folder(excel_file in my case), and after that using fgetcsv function read that csv file and added data into database.

$uploadedDocPath='excel_file/'; // folder name for document upload
if(move_uploaded_file($tmpDoc, $uploadedDocPath.$new_doc_name)){
   if(($handle = fopen("excel_file/".$new_doc_name , "r")) !== FALSE)
   {
   $fileAdded=true;
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
   {
      $num = count($data);
      $query="INSERT INTO csv_data(name,phone,city)
            values('".$data[0]."','".$data[1]."','".$data[2]."')";
      mysql_query($query);
   }
   fclose($handle);
  }
}

CSV Export  from MySql Database with PHP

Retrieve all the data from database using select query and forcefully append into define excel file.

$sql="select * from csv_data";
$res = mysql_query($sql);
$num=mysql_num_rows($res);
if($num > 0){
   echo 'S.No,Name,Phone,Email';
   echo "\r\n";
   $i=1;
   while($row=mysql_fetch_array($res)){
      echo $i.','.$row['name'].','.$row['phone'].','.$row['city'];
      echo "\r\n";
      $i++;
   }
}else{
   echo 'No Data Found';
}
$filename=date('d-m-y').'-export-report.csv';

/*Forcefully download csv file*/
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename='.$filename);

8 Comments

  1. Developer

    Looks good, but i don’t think, It will works well

  2. Alberti Steagal

    Useful info.

  3. Ethyl Cameli

    I like it.. Thanks

  4. Great post, you have pointed out some good details.

  5. Gawrys Landsman

    Thanks, this was the most useful PHP CSV introduction so far. Any Idea how to put XLS data directly into a MySQL database?

  6. Mayank Sharma

    It’s really a nice and useful piece of info. I am glad that you shared this helpful info with us

  7. Ram Arora

    Thank you so much for this.
    Can you please tell me how to import and export xml file.
    Cheers

  8. Prasad Rajapaksha

    I am trying to find something like this specific. Fantastic info


*

Copyright © 91 Web Lessons - a digital blog