从sql数据库下载php中的.csv文件时出错

时间:2013-04-07 07:22:09

标签: php sql phpmyadmin

我正在尝试从phpmyadmin数据库下载'.csv',但它下载了一些空白文件。 相同的查询适用于phpmyadmin中的sql。以下是代码:

function get_csv()
{ 
 $filename="c:/mydata.csv";
 $var=mysql_query("SELECT * INTO OUTFILE $filename FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY \"\n\" FROM course");
 header("Content-type:  text/plain");
 header("Content-Disposition: attachment; filename=$filename.xls");
 header("Content-Transfer-Encoding: binary");
 header("Pragma: no-cache");
 header("Expires: 0");
 //print "$header\n$data";
 return 0;
}

在取消注释print语句时,我得到一个显示错误的文件:

<br />
<b>Notice</b>:  Undefined variable: header in <b>C:\xampp\htdocs\SEN_PROJECT_Latest\SEN-PROJECT\class\database.php</b> on line <b>485</b><br />
<br />
<b>Notice</b>:  Undefined variable: data in <b>C:\xampp\htdocs\SEN_PROJECT_Latest\SEN-PROJECT\class\database.php</b> on line <b>485</b><br />

2 个答案:

答案 0 :(得分:0)

我猜你试图下载CSV文件,不需要依赖这个函数之外的其他变量,只需使用readfile()就可以看到正在下载的文件。

function get_csv()
{ 
  $filename="c:\\mydata.csv";
  $var=mysql_query("SELECT * INTO OUTFILE $filename FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY \"\n\" FROM course") or die(mysql_error());
  header("Content-type:  text/plain");
  header("Content-Disposition: attachment; filename=$filename.xls");
  header("Content-Transfer-Encoding: binary");
  header("Pragma: no-cache");
  header("Expires: 0");
  ob_clean();
  flush();
  readfile($filename);
  return 0;
}

如果该代码未下载该文件,您可以检查c:/mydata.csv并查看是否已创建。

答案 1 :(得分:0)

INTO OUTFILE中的文件名必须是字符串文字:

"SELECT * INTO OUTFILE '$filename' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY \"\n\" FROM course"