LatentDenis
LatentDenis

Reputation: 2991

exporting a .csv file from download button

EDIT: I changed "echo($row)" to "print_r($row)" and now the csv that's being downloaded has each array in parenthesis with all the data mentioned, but how do I customize the way it all can be printed?

Right now, it's printing:

Array ( [id]=>1 [firstname]=>"Timmy" ) Array ( ....

(where each line is the next row in the excel spreadsheet)

How would I make this output so that each record has it's own row? for example the first column in excel would be id, then the second would be firstname, with each record it's own row?

I've got a link in my main.php:

<a class="btn" href="export.php">Export</a>

Then here's my export.php file:

<?php

//open database connection
try {
    $db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',
                    'DBUSER',
                    'DBPASS');

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
    echo "did not connect...";
}

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

$sql = "SELECT * FROM table_name;";

$sth = $db->prepare($sql);
$sth->execute();

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

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

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

echo "\r\n";

fclose($data);

?>

Upvotes: 0

Views: 3559

Answers (2)

Jay Blanchard
Jay Blanchard

Reputation: 34426

In order to get an associative array to be placed properly into your file you'll need to parse the array and then put the line in the file:

while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
    $csv = implode(',', $row) . "\n";
    fwrite($data, $csv);
    print_r($csv);
}

Upvotes: 3

MDChaara
MDChaara

Reputation: 318

I assume your output should be a csv file with the date as a file name, am I correct?

Could you try this:

UPDATED CODE

<?php

//open database connection
try {
    $db = new PDO('mysql:host=localhost;dbname=DBNAME;charset=utf8',
                    'DBUSER',
                    'DBPASS');

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $ex) {
    echo "did not connect...";
}

$sql = "SELECT * FROM table_name";

$sth = $db->prepare($sql);
$sth->execute();

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

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

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

fclose($data);


?>

The code will break because the "." is in the wrong place.

$filename = date('d.m.Y').'.csv'; is not the same as $filename = 'date('d.m.Y').'.csv';

@NoReceipt4Panda: I can not comment so Code is updated. You should be using $sth = $db->prepare($sql); not $sth = $conn->prepare($sql);. You don't have a variable with the name $conn.

Upvotes: 1

Related Questions