Astrid
Astrid

Reputation: 1312

Generating a CSV download using PDO queries

I am trying to make a user able to download a CSV backup of all of their data on my server. This means i am trying to execute multiple query's and placing the results into a CSV file.

This is what i have so far:

    <?php
            // Connect
            include 'config.php'; // Config contains PDO database connection, etc.
                // Generate filename
                $filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';
                // Get backup data from MYSQL database
                $result_users = $conn->prepare('SELECT `user_name`, `user_email` FROM `users` WHERE `group_id` = ?');
                $result_users->execute(array($_SESSION['current_group_id']));
                $result_items = $conn->prepare('SELECT `item_name`, `item_value`, `item_group` FROM `items` WHERE `group_id` = ?');
                $result_items->execute(array($_SESSION['current_group_id']));
                # Create array
                $list = array ("## START OF USER TABLE ##");
                // Append results to array
                while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
                    array_push($list, array_values($row));
                }
                array_push($list,"## END OF USER TABLE ##");
                array_push($list,"## START OF ITEMS TABLE ##");
                while ($row = $result_items->fetch(PDO::FETCH_ASSOC)) {
                    array_push($list, array_values($row));
                }
                array_push($list,"## END OF ITEMS TABLE ##");

                // Output array into CSV file
                $fp = fopen('php://output', 'w');
                header('Content-Type: text/csv');
                header('Content-Disposition: attachment; filename="'.$filename.'"');
                foreach ($list as $ferow) {
                    fputcsv($fp, split(',',$ferow));
                }
    ?>

The expected output is supposed to be something like:

## START OF USERS TABLE ##
"John","john@email.com"
"James","james@email.com"
## END OF USERS TABLE ##

## START OF ITEMS TABLE ##
"Soap","A lot","Household"
"Banana","2","Food"
## END OF ITEMS TABLE ##

etc.

The problem is that the valued do not correctly get pushed into the $list array. What should i do in order to get the wanted result?

Thanks!

Upvotes: 3

Views: 15961

Answers (2)

Sbml
Sbml

Reputation: 1927

I think that your code its a little complicated for what you need. I don't test this code but probably works

$sql = "SELECT user_name, user_email FROM users WHERE group_id = :group_id
            UNION
            SELECT item_name, item_value, item_group FROM items WHERE group_id = :group_id
            ";

    $sth = $conn->prepare($sql);
    $sth->bindValue(':group_id', $_SESSION['current_group_id'], PDO::PARAM_INT);
    $sth->execute();

    $filename = $_SESSION['current_group'].'-'.date('d.m.Y').'.csv';

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

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

    fclose($data);

Upvotes: 10

Astrid
Astrid

Reputation: 1312

I solved it by doing the following:

            // Create array
            $list = array ();

            // Append results to array
            array_push($list, array("## START OF USER TABLE ##"));
            while ($row = $result_users->fetch(PDO::FETCH_ASSOC)) {
                array_push($list, array_values($row));
            }
            array_push($list, array("## END OF USER TABLE ##"));

            // Output array into CSV file
            $fp = fopen('php://output', 'w');
            header('Content-Type: text/csv');
            header('Content-Disposition: attachment; filename="'.$filename.'"');
            foreach ($list as $ferow) {
                fputcsv($fp, $ferow);
            }

Upvotes: 5

Related Questions