phpmysqlpdoexport-to-csv

Export Column Names to CSV


I'd would like to be able to export the names of my table columns into a .csv file along with my query results. I have found a few examples using mysql_, but I was hoping someone could help me out as I am trying to use PDOs. The data from $sql exports just fine, but I can't get the column names to export as the first row.

<?php 
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=brewlog.csv");
header("Pragma: no-cache");
header("Expires: 0");

//Database Connection 
include"connect.php";

//Assign variables from POST
    $beer = $_POST['beer'];

//SQL Query for Data
    $sql = "SELECT * FROM brewlog WHERE Beer = :beer ORDER BY BrewDate DESC";

//Prepare Query, Bind Parameters, Excute Query
    $STH = $DBH->prepare($sql);
    $STH->bindParam(':beer', $beer);
    $STH->execute();

//Get Column Names for Header   
    $STMT = $DBH->query('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = \'database\' AND TABLE_NAME = \'my_table\'');
    $header = $STMT->fetchAll(PDO::FETCH_NUM);

//Export to .CSV
    $fp = fopen('php://output', 'w');
    fputcsv($fp,$header);
    while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
    fclose($fp);
?>

Solution

  • You don't have to query the information_schema.
    Just fetch the row as an associative array and output the keys before you output the data:

    $row = $STH->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        fputcsv($fp,array_keys($row));
        while ($row) {
            fputcsv($fp, $row);
            $row = $STH->fetch(PDO::FETCH_ASSOC);
        }
    }