0

我正在尝试将 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();


?>

我希望它不是一个巨大的修复。我很感激任何帮助。谢谢你。

4

3 回答 3

3

为什么不简单地做

SELECT whatever
FROM your_table
INTO OUTFILE '/directory/file.csv'
FIELDS TERMINATED BY '|'
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

?

并从手册中:

...如果远程机器上安装了 MySQL 客户端软件,您可以使用 mysql -e "SELECT ..." > file_name 等客户端命令在客户端主机上生成文件

于 2013-08-02T14:19:25.653 回答
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);
于 2013-08-02T14:00:42.657 回答
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']);
于 2013-08-02T13:57:27.720 回答