2
Hello guys I am trying to create a php query in mysql database to generate a csv file according to the code below. The problem is that the part that would download the file is showing error, I already reviewed a few times and did not find the error I made. The file appears in the FTP folder where the index is.
I appreciate any help thank you very much.
<?php
//PDO
$pdo = new PDO('mysql:host=localhost;dbname=banco', 'root', '123456');
$stmt = $pdo->prepare('SELECT * FROM cadastro');
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
//Criação do Arquivo csv sobre os dados obtidos de um SQL
$from = fopen("file.csv", 'wb');
foreach ($results as $result)
{
$results[$idx] = str_replace("\"", "\"\"", $result);
fwrite($from, '"'.implode('";"', $results[$idx]).'"'.PHP_EOL);
}
fclose($from);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Content-Transfer-Encoding: binary");
header("Pragma: no-cache");
$path = "file.csv";
$from = fopen($path, 'r');
$csv = fread($from, filesize($path));
fclose($from);
echo $csv;
?>
This question is in the reopening queue. However, looking at the question, the answers and the comments in the answers, I get in doubt. Someone there might give reasons either to reopen or to keep it closed?
– Victor Stafusa