title: PHP - Export MySQL query to CSV Changeup
body: <p>I see plenty of postings about the proper ways to export to CSV, and most developers recommend to use <code>fputcsv()</code></p>
  
  <p>How would I convert the script below to use <code>fputcsv</code> ?
  You'll see I'm also exporting the Header row, which reflects the table column names, and I'd like to keep it.</p>
  
  <pre><code>&lt;?php
  
      $sql = "SELECT * FROM `tbl_customers`";
      $result = mysql_query($sql, $dbdata_conn) or die(mysql_error());
  
  
      $header = $csv_output = '';
      $fields = mysql_num_fields($result);
      for ($i = 0; $i &lt; $fields; $i++) {
          $header .= mysql_field_name($result, $i) . ",";
      }
      $header .= "\n";
  
      while ($rowr = mysql_fetch_row($result)) {
        for ($j=0; $j&lt;$i; $j++) {
          $csv_output .= $rowr[$j].", ";
            }
       $csv_output .= "\n";
      }
  
      $csv_output = $header.$csv_output;
  
      header("Content-type: text/x-csv");
      header("Content-Disposition: attachment; filename=test.csv");
      header("Pragma: no-cache");
      header("Expires: 0");
      print "$csv_output";
      exit;   
  
  ?&gt;
  </code></pre>
  
  <p>I'm aware that <code>mysql_query</code> is deprecated, so this is for the sake of practice.</p>
  
  <p>As a side note, I'm not familiar with <code>fputcsv</code>, but I am reading that it's rather useful for formatting the data for the csv output, saving us time with all the escapes and such.
  (I'm also very very open to improvements to what's above)</p>