user1286956
user1286956

Reputation: 299

Get mysql table columns names from database when exporting to csv

I'm exprting my databse in csv format, but I can't figure out how to export the mysql table columns names as well. Here is the code:

public function save($query)
    {
        $stmt = $this->db->prepare($query);
        $stmt->execute();

        /* header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=file.csv");
        header("Pragma: no-cache");
        header("Expires: 0");

        var_dump($stmt->fetch(PDO::FETCH_ASSOC));
        $data = fopen('/tmp/db_user_export_".time().".csv', 'w');
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
            echo "Success";
            fputcsv($data, $row);
        } */

        $list = array ();

            // Append results to array
            array_push($list, array("## START OF USER TABLE ##"));
            while ($row = $stmt->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="file.csv"');
            foreach ($list as $ferow) {
                fputcsv($fp, $ferow);
            }

    }

for the query:

include_once 'dbconfig.php';
$query = "SELECT * FROM users";
$crud->save($query);

The file.csv exports correctly but I would like to also include the names of the mysql table columns from where the values are being taken out from.

Thanks in advance!

Upvotes: 0

Views: 354

Answers (1)

user1286956
user1286956

Reputation: 299

I was having issues posting my table head into the csv so I took another approach. Hope it helps anyone that's trying to do what I'm doing:

public function export($table)
    {

        $stmt2 = $this->db->prepare("DESCRIBE ".$table);
        $stmt2->execute();

        if ($stmt2->rowCount()>0) {
         while ($row = $stmt2->fetch(PDO::FETCH_ASSOC)) {
          $csv_output .= $row['Field'].", ";
          $i++;
         }
        }
        $csv_output .= "\n";

        $stmt3 = $this->db->prepare("SELECT * FROM ".$table);
        $stmt3->execute();

        while ($rowr = $stmt3->fetch(PDO::FETCH_BOTH)) {
         for ($j=0;$j<$i;$j++) {
          $csv_output .= $rowr[$j].", ";
         }
         $csv_output .= "\n";
        }

        $filename = "raport_proiecte_".date("Y-m-d_H-i",time()).".csv";
        header("Content-Type: application/xls");    
        header("Content-Disposition: attachment; filename=$filename");  
        header("Pragma: no-cache"); 
        header("Expires: 0");
        print $csv_output;
        exit;

    }

Upvotes: 0

Related Questions