需要有关通过PHP将SQL导出为CSV的帮助

时间:2016-02-10 15:50:32

标签: php mysql csv mysqli

我有这个PHP脚本应该接受一个SQL查询并将其输出到一个CSV文件,我知道当我运行它时我得到了正确的语句,但它似乎没有生成文件到我的上传文件夹。

有人可以为我调试吗?

<?php
function ExportExcel($statement)
{

$filename = "uploads/".strtotime("now").'.csv';

$sql = mysql_query("$statement") or die(mysql_error());

$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename, "w");
$seperator = "";
$comma = "";

foreach ($row as $name => $value)
    {
        $seperator .= $comma . '' .str_replace('', '""', $name);
        $comma = ",";
    }

$seperator .= "\n";
fputs($fp, $seperator);

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

        foreach ($row as $name => $value) 
            {
                $seperator .= $comma . '' .str_replace('', '""', $value);
                $comma = ",";
            }

        $seperator .= "\n";
        fputs($fp, $seperator);
    }

fclose($fp);
echo "<a href='$filename'>Download</a>";
echo $statement;
}
else
{
    echo "error";
}


}
?>

如果某人有类似的脚本使用mysqli那就不错了

1 个答案:

答案 0 :(得分:0)

这是我使用MySqli在我的应用上使用的导出脚本的示例。这将让你开始......

<?php

    function ExportExcel($statement){

        $output = ""; 
        $sql = mysqli_query($db , $statement);
        $columns_total = mysqli_num_fields($sql);

        // Get The Field Name

        for ($i = 0; $i < $columns_total; $i++) {
        $heading = mysqli_fetch_field_direct($sql, $i);
        $output .= '"'.$heading->name.'",';
        }
        $output .="\n";

        // Get Records from the table

        while ($row = mysqli_fetch_array($sql)) {
        for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
        }
        $output .="\n";
        }

        // Download the file

        $filename = "CSV_NAME_GOES_HERE.csv";
        header('Content-type: application/csv');
        header('Content-Disposition: attachment; filename='.$filename);

        echo $output;
        exit;

    }

?>