当我拿结果时,在没有表信息的情况下,只存在表字段名称! 另一个问题是,一列中的所有信息。 这是我的代码:
<?php
if(isset($_POST['sub_csv'])){
$conn=mysql_connect("localhost","root","");
mysql_select_db("school",$conn);
$filename='uploads/'.strtotime("now").'.csv';
$fp=fopen($filename,"w");
$sql=mysql_query("SELECT * FROM student");
$num_rows=mysql_num_rows($sql);
if($num_rows >=1)
{
$row=mysql_fetch_assoc($sql);
$seperator="";
$comma="";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$name);
$comma=",";
}
$seperator .="\n";
fputs($fp,$seperator);
fclose($fp);
}
else
{
echo 'No record in database';
}
}
?>
答案 0 :(得分:0)
您可以使用直接fputcsv()函数来创建csv文件。请参阅以下示例代码并更改您的PHP代码。你会得到预期的结果。
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');
// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));
// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');
// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
更多内容如下: 1. http://code.stephenmorley.org/php/creating-downloadable-csv-files/ 2. http://php.net/manual/en/function.fputcsv.php
答案 1 :(得分:0)
现在你只获取第一行
$row=mysql_fetch_assoc($sql);
您需要使用类似while($row=mysql_fetch_assoc($sql)){..}
根据您提供的代码:
<?php
if(isset($_POST['sub_csv'])){
$conn=mysql_connect("localhost","root","");
mysql_select_db("school",$conn);
$filename='uploads/'.strtotime("now").'.csv';
$fp=fopen($filename,"w");
$sql=mysql_query("SELECT * FROM student");
$num_rows=mysql_num_rows($sql);
if($num_rows >=1)
{
while($row=mysql_fetch_assoc($sql)){
$seperator="";
$comma="";
foreach($row as $name => $value)
{
$seperator .= $comma . '' .str_replace('','""',$name);
$comma=",";
}
$seperator .="\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No record in database';
}
}
?>