你能发现foreach()错误的来源吗?

时间:2012-05-30 10:25:52

标签: php scripting

我正在编写一个脚本来将MySQL查询导出为CSV文件。到目前为止一切都那么好,除了我得到第二个foreach()语句的无效参数!我试图使用mysql_data_seek,但这并没有解决问题。 AFAK $row是一个数组,所以它应该可以工作。

<?php

$conn = mysql_connect("12**strong text**7.0.0.1", "root", "root") or die(mysql_error());
mysql_select_db("database", $conn); 

if(isset($_POST['submit']))
{
    $filename = 'uploads/'.strtotime("now").'.csv';

    $fp = fopen($filename,"w");

    $sql = mysql_query("SELECT * FROM master") or die(mysql_error());
    $row = mysql_fetch_assoc($sql);

    $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);
}


?>

1 个答案:

答案 0 :(得分:0)

我无法理解你为什么添加了第一个foreach循环,你的代码应该如下

<?php

$conn = mysql_connect("12**strong text**7.0.0.1", "root", "root") or die(mysql_error());
mysql_select_db("database", $conn); 

if(isset($_POST['submit']))
{
    $filename = 'uploads/'.strtotime("now").'.csv';

    $fp = fopen($filename,"w");

    $sql = mysql_query("SELECT * FROM master") or die(mysql_error());
    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);
}


?>