需要在php

时间:2015-12-04 20:06:16

标签: php

我有多个条件所以我试图生成一个函数来将sql数据下载到Csv文件。我在下载文件时遇到了麻烦。每当我尝试,页面只是重新加载和文件不下载。我不确定我做错了什么,因为当我使用echo命令时,我可以看到页面上显示的数据。如果有人可以帮助并指导我正确的方式,那将非常有帮助。

if(isset($_POST['report'])){
    $sql = mysql_query("SELECT rating_postid,rating_posttitle,COUNT(rating_rating) AS Count,AVG(rating_rating) as Average FROM wp_ratings WHERE 1=1
    GROUP BY rating_postid,rating_posttitle") or die(mysql_error());
    generate_csv($sql);
}

function generate_csv($sql){ 

    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private", false);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=data.csv');
    header("Content-Transfer-Encoding: binary");

    $num_rows = mysql_num_rows($sql);

    if($num_rows >= 1)
        {
            $row = mysql_fetch_assoc($sql);
            $fp = fopen('php://output','w');
            $sep = "";
            $comma= "";

    foreach($row as $name => $value)
    {
    $sep .= $comma . '' .STR_REPLACE('','""',$name);
    $comma = ",";
    }
    $sep .= "\n";

    fputs($fp,$sep);

    mysql_data_seek($sql,0);
    while($row = mysql_fetch_assoc($sql))
    {
    $sep = "";
    $comma= "";

    foreach($row as $name => $value)
    {
    $sep .= $comma . '' .STR_REPLACE('','""',$value);
    $comma = ",";
    }
    $sep .= "\n";
    fputs($fp,$sep);
    }
    fclose($fp);
    //echo $fp; 
    }
    else
    {
    echo 'NO RECORDS IN DATABASE';
    }

}

0 个答案:

没有答案