Currently, my code exports data to a CSV file and saves it on the server. But I want it to upload a file. How should I do it?

I tried to do this with headers in the past, but it either loaded an empty CSV file or the PHP file itself.

<?php
    $database = new PDO('mysql:host=localhost;dbname=DB_Name', "root", "");

    $sql = "SELECT Card_ID, Card_UID, Card_Type FROM cards";

    $stmt = $database->prepare($sql);
    $stmt->execute();

    $filename = 'MyCSVFile-'.date('Y-m-d').'.csv';

    $data = fopen($filename, 'w');

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        fputcsv($data, $row);
    }
    fclose($data);
?>
Run code
+4
source share
1 answer

Try so you can get your result.

<?php
$database = new PDO('mysql:host=localhost;dbname=DB_Name', "root", "");

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

$sql = "SELECT Card_ID, Card_UID, Card_Type FROM cards";

$stmt = $database->prepare($sql);
$stmt->execute();

$data = fopen('php://output', 'w');

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    fputcsv($data, $row);
}
fclose($data);

? >

+2
source

All Articles