我正在尝试将 mysql 查询导出到 csv。我让它工作,唯一的事情是它没有把空的字段放在那里。我用管道将它们分开,|。我需要能够下载查询并将其上传到其他地方,所以我需要它来导出空字段。这是我当前的导出代码:
<?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();
?>
我希望它不是一个巨大的修复。我很感激任何帮助。谢谢你。