简体   繁体   English

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

[英]How to insert sql query results in one single line in csv from php?

The following code output the sql query result into a csv file : 以下代码将sql查询结果输出到csv文件中:

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 OUTPUT

The csv file contains output in following format : csv文件包含以下格式的输出:

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

2,3,1,4,2,1-1-2000 #line2 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 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 ?? 谁在这里知道怎么做?

just concancenate the row, like below : 只是对行进行concancenate,如下所示:

// loop over the rows, outputting them
$arr1 = array();
while ($row = mysqli_fetch_assoc($result)){
   $arr1 = array_merge($arr1,array_values($row));
}
fputcsv($output,$arr1);

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. 注意:上面的代码将为您提供1行的所有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM