PHP 中的多维 Oracle 数据库数组问题

问题描述 投票:0回答:1

代码的问题是它仅在循环中写入最后一行(在文件中),因为它应该显示从数据库获取的所有数据。 但是 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 循环,但仍然是同样的问题

php arrays oracle fputcsv
1个回答
0
投票
  1. 整齐地格式化代码,以便缩进与每个(嵌套)控制语句的级别相匹配。
  2. 不要在每个循环中重新打开(并重新创建)文件。在开始时创建一次文件,然后在循环中写入该文件。
  3. 不要从数据库中重复
    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);
© www.soinside.com 2019 - 2024. All rights reserved.