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

skyzr88 发布于 2017/04/28 10:51
阅读 126
收藏 0
PHP

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

加载中
0
Tuesday
Tuesday

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

justintung
justintung
回复 @Tuesday : 我也是醉了,舅服你
Tuesday
Tuesday
回复 @justintung : 眼光要放远啊.
skyzr88
skyzr88
非常感谢,我的问题解决了!!!
justintung
justintung
为什么要在php7下测试呀
返回顶部
顶部