简体   繁体   中英

Need Table headings added to exported CSV file

I have a script that takes a SQL Statement and puts the query result into a CSV file. Right now it only the rows of the table, I want it to Put the headings of the table at the top. How would I do that with this current script?

Script...

<?php

include 'connect.php'; 

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename="export.csv"');
header('Cache-Control: max-age=0');

$fpcsv = fopen('php://output', "a+");

$sqlstatement = $_GET['sqlstatement'];
$exportcsv_q = mysql_query($sqlstatement);
if (@mysql_num_rows($exportcsv_q) > 0) {
    $campos = mysql_num_fields($exportcsv_q);
    while ($exportcsv_r = mysql_fetch_row($exportcsv_q)) {
         fputcsv($fpcsv, $exportcsv_r);
    }
}
exit;
?>

If anyone out there has a mysqli version of this I would love to be able to switch this over.

First, the answer to your question: output the headers before your while loop:

if (@mysql_num_rows($exportcsv_q) > 0) {
    // output headers here
    fwrite($fpcsv, "header1,header2,foo,bar,..."); // <-- like this
    // if you want, you could do it this way:
    // fputcsv($fpcsv, array("header1", "header2", ...));

    $campos = mysql_num_fields($exportcsv_q);
    while ($exportcsv_r = mysql_fetch_row($exportcsv_q)) {
         fputcsv($fpcsv, $exportcsv_r);
    }
}

If you want to have the headers even if there is no data, just move that line outside your if block, as well.

Second, yes, you should stop using mysql_* ; the mysql_* functions are outdated, deprecated , and insecure. Use MySQLi or PDO instead. How to do that is too broad for a single question here. If you get stuck on some aspect of it, ask a new question about that.

Third, swallowing/suppressing errors with @ is considered bad practice and can lead to unexpected results. Use a proper try { ... } catch (...) {...} block instead so you can handle/log/report the error as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM