I am trying to export a mysql query to csv. I have it working, the only thing is it's not putting the empty fields in there. I them separate by pipes, |. I need to be able to download the query and upload it somewhere else, so I need it to export the empty fields along with it. Here is my current export code:
<?php
$from = $_REQUEST['from'];
$to = $_REQUEST['to'];
$filename = "APGE_ELEC_" . $to;
header('Content-Disposition: attachment; filename="'.$filename.'".csv"');
$hostname = ""; //SET SERVER/HOSTNAME
$dbusername = ""; //SET DATABASE USERNAME
$dbname = ""; //SET DATABASE NAME
$dbpassword = ""; //SET DATABASE USERNAME
$dbhandle = mysql_connect($hostname, $dbusername, $dbpassword)
or die("Unable to connect to MySQL");
$selected = mysql_select_db($dbname,$dbhandle)
or die("Could not select Data Base");
$query = "SELECT * FROM v88374 WHERE date >= DATE_FORMAT('" . $from . "', '%Y%m%d') AND date <= DATE_FORMAT('" . $to . "', '%Y%m%d')";
$export = mysql_query ($query ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) ."|" . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = $value . '|' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
print "$header\n$data";
exit();
?>
I hope its not a huge fix. I appreciate any help. Thank you.
aynber :
To use fputcsv, try this:\n\n$fp = fopen('your_file_name.csv','w');\nfputcsv($fp,$fields,'|'); // add in your header row\nwhile( $row = mysql_fetch_row( $export ) )\n{\n if($row != NULL)\n fputcsv($fp,$row,'|'); // Each row is already an array, so you just need to export it here\n}\nfclose($fp);\n",
2013-08-02T14:00:42
fancyPants :
Why not simply do\n\nSELECT whatever\nFROM your_table\nINTO OUTFILE '/directory/file.csv'\nFIELDS TERMINATED BY '|'\nENCLOSED BY '\"'\nLINES TERMINATED BY '\\n'\n\n\n?\n\nAnd from the manual:\n\n\n ... if the MySQL client software is installed on the remote machine, you can instead use a client command such as mysql -e \"SELECT ...\" > file_name to generate the file on the client host\n",
2013-08-02T14:19:25