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);
?>