Skip to content
Advertisement

PHP copying the result from a SQL Query into a CSV file writes only the last line

I’m trying to take some results from a query that I do to Oracle and paste them on a CSV file, the problem is that, in the foreach loop, the code should writes line by line, but he writes only the last line and I’m not able to understand the reason.

In the code I write an header of the csv file as you can see below, and this part is written in the csv file but then when I start the foreach loop he “sees” every line (because I tried to do a var_dump at every loop) but he writes only the last one.

The $res->rows is the variable that contains the rows outputted by the query.

$handle = fopen(Configuration::EXPORT_UPLOAD_PATH . DIRECTORY_SEPARATOR . explode('.', self::UPDATE_STATO_LIBRO_QUESTURA_TEMPLATE_FILE_NAME)[0] . '_BU_' . date("dmY") . '.csv', "w");
fwrite($handle, self::LIBRO_QUESTURA_UPDATE_COLUMN_NAME_NUMERO_PROTOCOLLO . ';');
fwrite($handle, self::LIBRO_QUESTURA_UPDATE_COLUMN_NAME_TRANCHE_MASSIVA . '_OLD;');
fwrite($handle, self::LIBRO_QUESTURA_UPDATE_COLUMN_NAME_TIPO_MANDATO . '_OLD;');
fwrite($handle, self::LIBRO_QUESTURA_UPDATE_COLUMN_NAME_COND_ECONOMICHE . '_OLD;');
fwrite($handle, self::LIBRO_QUESTURA_UPDATE_COLUMN_NAME_NUMERO_CONTRATTO . '_OLD' . PHP_EOL);
foreach($res->rows as $libroQuestura) {
    fputcsv($handle, $libroQuestura, ";");
}
fclose($handle);

Advertisement

Answer

With fopen – to append contents to a file use the ‘a’ parameter not ‘w’

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement