<?php
/*
* PHP code to export MySQL data to CSV
*
* Sends the result of a MySQL query as a CSV file for download
* Easy to convert to UTF-8.
*/
/*
* establish database connection
*/
$conn = mysql_connect('localhost', 'root', 'porsche911') or die(mysql_error());
mysql_select_db('mysql', $conn) or die(mysql_error($conn));
mysql_query("SET NAMES UTF-8");
/*
* execute sql query
*/
$query = sprintf("SELECT listid,workdate,worker.w_name,sub_info,p_name,quantity,p_price,this_price,subtotal,subtotal2 FROM worker,p_info,p_sub,worklist where PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( workdate, '%Y%m' ) ) =1 AND worker.w_id=worklist.w_id
and worklist.p_id=p_info.p_id
and p_info.sub_id=p_sub.sub_id order by w_name; ");
$result = mysql_query($query, $conn) or die(mysql_error($conn));
/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment;filename=shangyue.csv');
/*
* output header row (if atleast one row exists)
*/
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array_keys($row));
}
/*
* output data rows (if atleast one row exists)
*/
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
/*
* echo the input array as csv data maintaining consistency with most CSV implementations
* - uses double-quotes as enclosure when necessary
* - uses double double-quotes to escape double-quotes
* - uses CRLF as a line separator
*/
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
以上代码一运行就提示Warning: sprintf(): Too few arguments in C:\AppServ\www\jayi v1.0\phpcsv_shangyue(ce).php on line 21
Query was empty,本人是个菜鸟,还请大神指教,数据库语句在mysql里面可以执行,并不报错,能查询到正确的数据。
sprintf删除即可. 建议在php7下面测试.
回复 @Tuesday:我也是醉了,舅服你回复 @justintung:眼光要放远啊.非常感谢,我的问题解决了!!!为什么要在php7下测试呀版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。