title: How to convert mysql table data to Excel or CSV format in CakePHP?
body: <p>I want to convert my sql data to csv files while clicking on a button. The code fragments I found for sql to CSV conversion were in PHP, and I'm trying to convert it to CakePHP since I'm working in CakePHP.</p>
  
  <p>Here is the PHP code I'm tring to convert:</p>
  
  <pre><code>$result = mysql_query("SHOW COLUMNS FROM ".$table."");
  $i = 0;
  if (mysql_num_rows($result) &gt; 0) {
     while ($row = mysql_fetch_assoc($result)) {
          $csv_output .= $row['Field']."; ";
          $i++;
     }
  }
  $csv_output .= "\n";
  
  $values = mysql_query("SELECT * FROM ".$table."");
  while ($rowr = mysql_fetch_row($values)) {
      for ($j=0;$j&lt;$i;$j++) {
             $csv_output .= $rowr[$j]."; ";
      }
      $csv_output .= "\n";
  }
  
  $filename = $file."_".date("Y-m-d_H-i",time());
  header("Content-type: application/vnd.ms-excel");
  header("Content-disposition: csv" . date("Y-m-d") . ".csv");
  header( "Content-disposition: filename=".$filename.".csv");
  print $csv_output;
  </code></pre>
  
  <p><strong>SOLUTION</strong></p>
  
  <p>Function in the Controller:</p>
  
  <pre><code>function exporttocsv()
  {       
   $this-&gt;set('headers',$this-&gt;Result-&gt;find('all',array('fields'=&gt;'Result.label')));
   $this-&gt;set('values',$this-&gt;Result-&gt;find('all',array('fields'=&gt;'Result.value')));       
  }
  </code></pre>
  
  <p>exporttocsv.ctp file:</p>
  
  <pre><code>&lt;?php
  
  foreach($headers as $header):
  
       $csv_output .=$header['Result']['label'].", ";
  
  endforeach;
  $csv_output .="\n";
  
  if(!empty($values)){
  foreach($values as $value):
  
       $csv_output .=$value['Result']['value'].", ";
  
  endforeach;
  $csv_output .="\n";
  }
  else{
  echo "There is no data to export.";
  }
  
  $filename = "export_".date("Y-m-d_H-i",time());
  header("Content-type: application/vnd.ms-excel");
  header("Content-disposition: csv" . date("Y-m-d") . ".csv");
  header("Content-disposition: filename=".$filename.".csv");
  
  print $csv_output;
  
  exit;
  ?&gt;
  </code></pre>