代码的问题是它仅在循环中写入最后一行(在文件中),因为它应该显示从数据库获取的所有数据。 但是 echo 函数确实打印出所有数据 但 fputcsv 只写最后一行
脚本
include 'includes/connection.php';
$date = date('d-M-Y');
$query = "SELECT DISTINCT
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
LCM.something1
FROM DB.something1 LCM
WHERE LCM.something1 = 'ASAS' ";
$array = oci_parse($conn, $query);
$run = oci_execute($array);
while($row=oci_fetch_array($array)){
$CMCF06 = $row[0] ;
$CMCF08 = $row[9] ;
$CMCF09 = $row[12];
echo $CMCF06 .'<br>';
$data = [
['HDHD', '2C4L20018', $date, $date, '081054','002'],
['CMCF', '2C4L20018', '', '0100', '',$CMCF06, '', $CMCF08, $CMCF09],
];
$filename = 'file.csv';
// open csv file for writing
$f = fopen($filename, 'w');
if ($f === false) {
die('Error opening the file ' . $filename);
}
// write each row at a time to a file
foreach ($data as $fields) {
fputcsv($f, $fields, '|');
}
}
echo 'done<br>';
// close the file
fclose($f);
我尝试了 while 循环和 foreach 循环,但仍然是同样的问题
SELECT
同一列(因为这是毫无意义的)。你想要这样的东西(未经测试):
include 'includes/connection.php';
$date = date('d-M-Y');
$filename = 'file.csv';
// open csv file for writing
$f = fopen($filename, 'w');
if ($f === false) {
die('Error opening the file ' . $filename);
}
fputcsv($f, ['HDHD', '2C4L20018', $date, $date, '081054','002'], '|');
$query = "SELECT DISTINCT
LCM.something1
LCM.something2
LCM.something3
LCM.something4
LCM.something5
LCM.something6
LCM.something7
LCM.something8
LCM.something9
LCM.something10
LCM.something11
LCM.something12
LCM.something13
LCM.something14
LCM.something15
FROM DB.something1 LCM
WHERE LCM.something1 = 'ASAS'";
$array = oci_parse($conn, $query);
$run = oci_execute($array);
while($row=oci_fetch_array($array)){
$CMCF06 = $row[0] ;
$CMCF08 = $row[9] ;
$CMCF09 = $row[12];
echo $CMCF06 .'<br>';
fputcsv($f, ['CMCF', '2C4L20018', '', '0100', '',$CMCF06, '', $CMCF08, $CMCF09], '|');
}
echo 'done<br>';
// close the file
fclose($f);