简体   繁体   English

将需要表标题添加到导出的CSV文件中

[英]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. 我有一个采用SQL语句并将查询结果放入CSV文件的脚本。 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. 如果有人在那里有这个的mysqli版本,我希望能够切换到这个版本。

First, the answer to your question: output the headers before your while loop: 首先,您的问题的答案:在while循环之前输出标头:

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. 如果即使没有数据也要具有标题,也可以将该行移至if块之外。

Second, yes, you should stop using mysql_* ; 其次,是的,您应该停止使用mysql_* the mysql_* functions are outdated, deprecated , and insecure. mysql_*函数已过时, 过时和不安全。 Use MySQLi or PDO instead. 改用MySQLiPDO 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. 请改用适当的try { ... } catch (...) {...}块,以便您可以根据需要处理/记录/报告错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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