[英]Export Column Names to CSV
I'd would like to be able to export the names of my table columns into a .csv file along with my query results. 我希望能够将表列的名称与查询结果一起导出到.csv文件中。 I have found a few examples using mysql_, but I was hoping someone could help me out as I am trying to use PDOs. 我已经找到了一些使用mysql_的示例,但是我希望有人在尝试使用PDO时可以帮助我。 The data from $sql exports just fine, but I can't get the column names to export as the first row. 来自$ sql的数据可以正常导出,但是我无法获取要导出为第一行的列名称。
<?php
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=brewlog.csv");
header("Pragma: no-cache");
header("Expires: 0");
//Database Connection
include"connect.php";
//Assign variables from POST
$beer = $_POST['beer'];
//SQL Query for Data
$sql = "SELECT * FROM brewlog WHERE Beer = :beer ORDER BY BrewDate DESC";
//Prepare Query, Bind Parameters, Excute Query
$STH = $DBH->prepare($sql);
$STH->bindParam(':beer', $beer);
$STH->execute();
//Get Column Names for Header
$STMT = $DBH->query('SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = \'database\' AND TABLE_NAME = \'my_table\'');
$header = $STMT->fetchAll(PDO::FETCH_NUM);
//Export to .CSV
$fp = fopen('php://output', 'w');
fputcsv($fp,$header);
while ($row = $STH->fetch(PDO::FETCH_NUM)) fputcsv($fp,$row);
fclose($fp);
?>
You don't have to query the information_schema. 您不必查询information_schema。
Just fetch the row as an associative array and output the keys before you output the data: 只需将行作为关联数组获取并输出键,然后再输出数据:
$row = $STH->fetch(PDO::FETCH_ASSOC);
if ($row) {
fputcsv($fp,array_keys($row));
while ($row) {
fputcsv($fp,array_values($row));
$row = $STH->fetch(PDO::FETCH_ASSOC);
}
}
It looks like question should actually be "How do I get an array of my table's column names using PDO?" 看起来问题实际上应该是“如何使用PDO获取表的列名称的数组?” As found in another SO question. 正如在另一个SO问题中发现的那样。
$result = $db->query('SELECT * FROM my_table LIMIT 0');
for ($i = 0; $i < $result->columnCount(); $i++) {
$col = $result->getColumnMeta($i);
$columns[] = $col['name'];
}
Then do the array to CSV. 然后将数组转换为CSV。
$fp = fopen('php://output', 'w');
fputcsv($fp, $columns);
And here's another way that is not "experimental"... 这是另一种不是“实验”的方式...
$q = $db->prepare("DESCRIBE tablename");
$q->execute();
$columns = $q->fetchAll(PDO::FETCH_COLUMN);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.