[英]Exporting SQL table to CSV, column names not appearing
所以這是我目前用於將特定表導出為.csv格式的代碼。 它到目前為止工作得很好,因為它下載文件並根據我的需要格式化數據。 但是它不顯示列名稱
例如:目前顯示
1瓊斯馬特
2史密斯約翰
3 Doe Jane
我希望它顯示:
ID Last_Name First_Name
1瓊斯馬特
2史密斯約翰
3 Doe Jane
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT * FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['ID']},";
$result.="{$row['LAST_NAME']},";
$result.="{$row['FIRST_NAME']},";
$result.="{$row['ORGANIZATION']},";
$result.="{$row['TITLE']},";
$result.="\n";
}
echo $result;
?>
這是添加列名稱的快速而又臟的方法:
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT * FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
// -------------------- add the line below -----------------------------------
$result="ID,LAST_NAME,FIRST_NAME,ORGANIZATION,TITLE\n";
// -------------------- add the line above -----------------------------------
while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
$result.="{$row['ID']},";
$result.="{$row['LAST_NAME']},";
$result.="{$row['FIRST_NAME']},";
$result.="{$row['ORGANIZATION']},";
$result.="{$row['TITLE']},";
$result.="\n";
}
echo $result;
?>
只需在while
循環之前添加標題行:
echo "ID,Last_Name,First_Name,ORGANIZATION,TITLE\n";
我假設您還想查詢列名稱。
使用SELECT語句,您將永遠不會在結果中獲取列名。
在MySQL中你可以使用
SHOW COLUMNS FROM applications FROM db;
獲取結果中的列名稱。
另一種實現方式是允許您使用fputcsv來防止數據中的逗號。
<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=applications.csv");
header("Pragma: no-cache");
header("Expires: 0");
ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);
mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$query = "SELECT ID, LAST_NAME, FIRST_NAME, ORGANIZATION, TITLE FROM applications";
$select_c = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($select_c, MYSQL_ASSOC);
$fp = fopen("php://output", "w");
fputcsv($fp, array_keys($row));
do {
fputcsv($fp, $rows);
} while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC));
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.