如何在 PHP/SQL 生成的.csv电子表格中设置列名


How to set column names in PHP/SQL generated .csv spreadsheet

>我在网上找到了以下脚本并根据我的需要进行编辑,但我无法弄清楚的一件事是如何更改列名。按原样,列名在电子表格中显示为数据库中相应列的名称。有没有办法改变这一点?

感谢您的任何建议!这是我的代码:

<?php
$host = 'asdf';
$user = 'asdf';
$pass = 'asdf';
$db = 'asdf';
$table = 'stats';
$file = 'export';
    $fields = "date, name, time, inbset, asapset, faxset, obset, totset, inbclo, asapclo, faxclo, obclo, totclo, inbtot, asaptot, faxtot, obtot, total, comments";
$filename = $file."_".date("Y-m-d");
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "'n";
$values = mysql_query("SELECT $fields FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "'n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
exit;
?>

列名称来自 CSV 输出中的第一行。

20号线周围: $csv_output .= $row['Field'].", " ;

只需删除该代码块,然后输出一行列名,如您所愿:"列名 1、列名 2、列名 3、..."

你那里的代码 - 可能是复制和粘贴而不是你自己编写和理解的 - 是精神分裂症。

一方面,它确实定义了顶部的列名:

    $fields = "date, name, time, inbset, asapset, faxset, obset, totset, inbclo, asapclo, faxclo, obclo, totclo, inbtot, asaptot, faxtot, obtot, total, comments";

另一方面,它从数据库中读取它们:

$result = mysql_query("SHOW COLUMNS FROM ".$table."");

我建议您创建第二个变量,该变量仅包含CSV文件的列名称,并将其作为文件的第一行放入文件中。工作完成。

生成标题行的行是:

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "'n";

因此,要根据需要标题行,您需要修改此代码。如果您不需要它,它也会为您节省数据库查询

您应该

在选择时使用"AS"。

例如,我得到了一个桌子的人:

id,username,name,birth
1,alpera,aykutalper,1985

如果我使用

select username from people where id=1;
this returns
|username|
|alpera  |

如果我使用

select username as user from people where id=1;
this returns
|user    |
|alpera  |

我希望这就是你想要的。