开发者社区> 问答> 正文

请教一个关于PHP导出CSV的问题??报错

<?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里面可以执行,并不报错,能查询到正确的数据。

展开
收起
爱吃鱼的程序员 2020-06-08 15:10:50 497 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    sprintf删除即可.  建议在php7下面测试. 

    回复 @Tuesday:我也是醉了,舅服你回复 @justintung:眼光要放远啊.非常感谢,我的问题解决了!!!为什么要在php7下测试呀
    2020-06-08 15:11:09
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
阿里云栖开发者沙龙PHP技术专场-深入浅出网络编程与swoole内核-吴镇宇 立即下载
PHP安全开发:从白帽角度做安全 立即下载
PHP 2017.北京 全球开发者大会——高可用的PHP 立即下载