我正在尝试将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();
?>
我希望它不是一个巨大的修复。我感谢任何帮助。谢谢。
答案 0 :(得分:3)
为什么不简单地做
SELECT whatever
FROM your_table
INTO OUTFILE '/directory/file.csv'
FIELDS TERMINATED BY '|'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
来自manual:
...如果MySQL客户端软件安装在远程计算机上,您可以改为使用客户端命令,例如mysql -e“SELECT ...”&gt; file_name在客户端主机上生成文件
答案 1 :(得分:1)
要使用fputcsv,请尝试以下方法:
$fp = fopen('your_file_name.csv','w');
fputcsv($fp,$fields,'|'); // add in your header row
while( $row = mysql_fetch_row( $export ) )
{
if($row != NULL)
fputcsv($fp,$row,'|'); // Each row is already an array, so you just need to export it here
}
fclose($fp);
答案 2 :(得分:0)
我认为错误就在这里:
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = $value . '|' . "\t";
}
$line .= $value;
当$ value为空时,你将它设为一个标签并在没有管道的情况下添加它,else语句中的内容不会被执行。
此外,您的查询也存在严重的安全问题,因此除非仅供个人使用,并且对查询有一定的卫生条件。
$from = mysql_real_escape_string($_REQUEST['from']);
$to = mysql_real_escape_string($_REQUEST['to']);