1

我有这段代码可以将 MySQL 数据导出到 CSV 文件,但是当我回显结果时,它只显示数据库中的 1 行,即使我在 PHP My Admin 中运行 SQL,它也会显示大约 29 行。

它只是生成一个空白的 CSV 文件

$sql="select description, jobreceived, timebookedfor, bookedfor,
      site_contact, site_address, invoice_contact, invoice_address,
      quotedprice, cleardowndetails, notes, mo_number from jobs ";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$filename="jobs.csv";
$file=fopen($filename,"w");
//$output="sequence,firstname,surname,email,membertype\n";
fwrite($file,$output);
while($result=mysql_fetch_array($rs))
{
    echo $result["description"].','.$result["jobreceived"].'<br>';
    //$output=$result["sequence"].",".$result["name"].","
              .$result["email"].",".$result["country"]."\n";
    $output=proper($result["description"]).",".$result["jobreceived"]
           ."\r\n";
    fwrite($file,$output);
}
fclose($file);
function proper($string)
{
    $first=strtoupper(substr($string,0,1));
    $rest=strtolower(substr($string,1));
    $result=$first.$rest;
    return $result;
}
4

2 回答 2

0

也许您应该尝试删除 fwrite($file,$output); 循环中的语句。如果查询结果按预期回显,那么问题显然是 fwrite 语句(可能是文件权限)。如果结果未按预期回显,则您的查询结果可能存在问题。此外,作为建议,请确保按照 fopen 手册的规定,为操作系统使用正确的行尾字符。

于 2013-04-23T09:50:05.700 回答
0

你可以用这两个函数来做

function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
{
    if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
    {
        show_error('You must submit a valid result object');
    }

    $out = '';

    // First generate the headings from the table column names
    foreach ($query->list_fields() as $name)
    {
        $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
    }

    $out = rtrim($out);
    $out .= $newline;

    // Next blast through the result array and build out the rows
    foreach ($query->result_array() as $row)
    {
        foreach ($row as $item)
        {
            $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
        }
        $out = rtrim($out);
        $out .= $newline;
    }

    return $out;
}

function write_file($path, $data, $mode = 'wb')
{
    if ( ! $fp = @fopen($path, $mode))
    {
        return FALSE;
    }

    flock($fp, LOCK_EX);
    fwrite($fp, $data);
    flock($fp, LOCK_UN);
    fclose($fp);

    return TRUE;
}

将您的查询对象传递给函数。

$sql="select
          description,
          jobreceived,
          timebookedfor,
          bookedfor,
          site_contact,
          site_address,
          invoice_contact,
          invoice_address,
          quotedprice,
          cleardowndetails,
          notes,
          mo_number
        from jobs";
$rs =   mysql_query($sql,$conn) or die(mysql_error());

现在将资源传递给csv_from_result函数

$file_data  =   csv_from_result($rs);

现在你可以写文件了

$filename   =   "jobs.csv"; 
write_file($filename , $file_data); // $filename can be a complete path

或回显查看 csv 结果

echo $file_data;
于 2013-04-23T09:27:15.673 回答