By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,655 Members | 1,860 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,655 IT Pros & Developers. It's quick & easy.

Export data in excel format using datepicker in php & mysql

P: 40
hi,
I managed to export whole table using following code. Now I want to export data to excel using from and to date or using any date picker.

Expand|Select|Wrap|Line Numbers
  1. <?php
  2. //include 'connectdb.php';
  3.  
  4.  
  5. mysql_connect("localhost", "root", "123") or die(mysql_error());
  6. mysql_select_db("nadaehsan") or die(mysql_error());
  7.  
  8.  
  9.  
  10.  
  11. $count = 0;
  12. $sqlquery = "select * from main" ;
  13. $result = mysql_query($sqlquery) or die(mysql_error());  
  14. $count = mysql_num_fields($result);
  15. $header = '';
  16. $data ='';
  17.  
  18. for ($i = 0; $i < $count; $i++) {
  19.     $header .= mysql_field_name($result, $i)."\t";
  20. }
  21.  
  22. while($row = mysql_fetch_row($result))  {
  23.   $line = '';
  24.   foreach($row as $value)       {
  25.     if(!isset($value) || $value == "")  {
  26.       $value = "\t";
  27.     }   else  {
  28. # important to escape any quotes to preserve them in the data.
  29.       $value = str_replace('"', '""', $value);
  30. # needed to encapsulate data in quotes because some data might be multi line.
  31. # the good news is that numbers remain numbers in Excel even though quoted.
  32.       $value = '"' . $value . '"' . "\t";
  33.     }
  34.     $line .= $value;
  35.   }
  36.   $data .= trim($line)."\n";
  37. }
  38. # this line is needed because returns embedded in the data have "\r"
  39. # and this looks like a "box character" in Excel
  40.   $data = str_replace("\r", "", $data);
  41.  
  42.  
  43. # Nice to let someone know that the search came up empty.
  44. # Otherwise only the column name headers will be output to Excel.
  45. if ($data == "") {
  46.   $data = "\no matching records found\n";
  47. }
  48.  
  49. $count = mysql_num_fields($result);
  50.  
  51.  
  52.  
  53. # This line will stream the file to the user rather than spray it across the screen
  54.  header("Content-type: application/octet-stream");
  55. //header("Content-type: text/plain");
  56.  
  57. # replace excelfile.xls with whatever you want the filename to default to
  58. header("Content-Disposition: attachment; filename=excelfile.xls");
  59.  
  60. header("Pragma: no-cache");
  61. header("Expires: 0");
  62.  
  63. //echo $header."\n".$data;
  64. echo $header."\n".$data."\n";
  65. ?>
  66.  
  67.  


I am new in PHP and mysql so please help out me..Thanks
May 8 '15 #1
Share this question for a faster answer!
Share on Google+

Post your reply

Sign in to post your reply or Sign up for a free account.