0

I have a database with two tables: core_members and core_fields_content.

core_members has the columns: member_id, name, email core_pfields_content has the columns: member_id, field_1, field_2, etc.

I'd like to output the results of a query which selects the names and emails of the members, according to the custom field value provided in the query and export this to a csv file.

I want the output to appear in columns, but when opened in excel, the code below gives me the following output all in one cell: name;email;test name;testemail@test.com;

How can I change the code to output into columns, with the column name as a heading?

<?php

    $csv_fileName = 'forumuserlist_'.date('Y-m-d').'.csv';

    // database variables
    $hostname = "localhost";
    $user = "";
    $password = "";
    $database = "";

    // Database connecten voor alle services
    mysql_connect($hostname, $user, $password)
    or die('Could not connect: ' . mysql_error());

    mysql_select_db($database)
    or die ('Could not select database ' . mysql_error());

    $csv_export = '';

    $query = mysql_query("SELECT m.name, m.email FROM core_members m, core_pfields_content p WHERE m.member_id=p.member_id AND p.field_4='LPC'");
    $field = mysql_num_fields($query);

    // create line with field names
    for($i = 0; $i < $field; $i++) {
      $csv_export.= mysql_field_name($query,$i).';';
    }
    $csv_export.= '';
    while($row = mysql_fetch_array($query)) {
      // create line with field values
      for($i = 0; $i < $field; $i++) {
        $csv_export.= $row[mysql_field_name($query,$i)].';';
      } 
      $csv_export.= ''; 
    }

    // Export the data and prompt a csv file for download
    header("Content-type: text/x-csv");
    header("Content-Disposition: attachment; filename=".$csv_fileName."");
    echo($csv_export);
?>
lcheney
  • 75
  • 5
  • check this: http://php.net/manual/en/function.fputcsv.php – vaso123 Nov 13 '14 at 16:02
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). You will also want to [Prevent SQL Injection!](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Jay Blanchard Nov 13 '14 at 16:05
  • @JayBlanchard to be honest i don't know what i'm doing, it's code i found on the internet and then wrote my own query! – lcheney Nov 13 '14 at 16:09

1 Answers1

1

change the separator from ; to , (COMMA separated values => csv) and enclose the columnnames and values between double quotes

RichardBernards
  • 3,146
  • 1
  • 22
  • 30