dongyuan1970
2017-03-19 09:05
浏览 66
已采纳

如何在php的csv中将sql查询结果插入一行?

The following code output the sql query result into a csv file :

CODE

<?php
// Report all errors except E_NOTICE   
error_reporting(E_ALL ^ E_NOTICE); 

//connection file
include("connection.php");  

$query      = 'SELECT resting_blood_sugar,serum_cholesterol,thalach,oldpeak,result,date from hd_test WHERE patient_id = 2';         
$output = fopen('N:\oldpatientgraph.csv', 'w');
$result = mysqli_query($link,$query);

// loop over the rows, outputting them
while ($row = mysqli_fetch_assoc($result)) fputcsv($output, $row);

?>

OUTPUT

The csv file contains output in following format :

1,1,1,1,1,11-1-2015 #line1

2,3,1,4,2,1-1-2000 #line2

Whereas i want to output the result in one line as follows :

1,1,1,1,1,11-1-2015,2,3,1,4,2,1-1-2000 #line1

Anyone here who knows how to do this ??

图片转代码服务由CSDN问答提供 功能建议

以下代码将sql查询结果输出到csv文件中:

CODE

 &lt;?php 
 //报告除E_NOTICE 
error_reporting之外的所有错误(E_ALL ^ E_NOTICE);  
 
 //连接文件
include(“connection.php”);  
 
 $ query ='SELECT resting_blood_sugar,serum_cholesterol,thalach,oldpeak,result,date from hd_test WHERE patient_id = 2';  
 $ output = fopen('N:\ oldpatientgraph.csv','w'); 
 $ result = mysqli_query($ link,$ query); 
 
 //循环遍历行,输出它们
while  ($ row = mysqli_fetch_assoc($ result))fputcsv($ output,$ row); 
 
?&gt; 
   
 
 

OUTPUT

csv文件包含以下格式的输出:

1,1,1,1,1,11-1-2015#line1 < / p>

2,3,1,4,2,1-1-2000#line2

我希望将结果输出到一行,如下所示 :

1,1,1,1,1,11-1-2015,2,3,1,4,2,1-1-2000#line1 \ n

任何人都知道如何做到这一点??

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongtuan1980 2017-03-19 09:12
    已采纳

    just concancenate the row, like below :

    // loop over the rows, outputting them
    $arr1 = array();
    while ($row = mysqli_fetch_assoc($result)){
       $arr1 = array_merge($arr1,array_values($row));
    }
    fputcsv($output,$arr1);
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duanpa1980 2017-03-19 09:34

    You can try this

    $output = fopen('N:\oldpatientgraph.csv', 'w');
    $csvString = '';
    $index = 0;
    while ($row = mysqli_fetch_assoc($result)){
      if ($key) {
        $csvString.=',';
      }
      $csvString .= implode(',',array_values($row)); #Array values to string
      $index = 1;
    }
    
    fwrite($output, $csvString); #Write string to file
    fclose($output);
    

    Note : Above code will give you all data in 1 line.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题