我有这个代码将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;
}
答案 0 :(得分: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;
答案 1 :(得分:0)
也许你应该尝试删除fwrite($ file,$ output);循环语句。如果查询结果按预期回显,则问题显然是fwrite语句(可能是文件权限)。 如果结果未按预期回显,则查询结果可能存在问题。 此外,作为建议,请确保为操作系统使用正确的行尾字符,如fopen手册所示。