Hello everyone, I'm trying to create a query in php in the mysql database to generate a csv file according to the code below. The problem is that the one that would download the file is presenting an error, I have reviewed it a few times and I did not find the error that I made. The file appears in the FTP folder where the index is.
Thank you for 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;
?>