<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('field1', 'field2', 'field3'));
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$rows = mysql_query('SELECT field1,field2,field3 from table');
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>
是可行的,但如何在结果中使用“where field1 like %%”
答案 0 :(得分:0)
我不确定我是否完全理解这个问题。
如果要查询数据库并从返回的结果中生成csv,其中csv中的每一行都有像[something]这样的field1,那么最好直接在查询中包含条件:
$queryStr = "select field1, field2, field3 from table where field1 like '%something%'";
$rows = mysql_query($queryStr);
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
这样您就不会返回超出需要的信息。
除此之外,不推荐使用mysql_ *函数,使用mysqli可能是个好主意。
答案 1 :(得分:0)
$rows = mysql_query("SELECT field1,field2,field3 from table where field1 like '%something%'");
REPLACE
$rows = mysql_query("SELECT field1,field2,field3 from table where field1 like 'something%'");
首先要删除
%
最终工作
<?php
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');
$output = fopen('php://output', 'w');
fputcsv($output, array('field1', 'field2', 'field3'));
mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$rows = mysql_query("SELECT field1,field2,field3 from table where field1 like 'something%'");
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);
?>