简体   繁体   English

从MySQL中的自定义查询输出列名

[英]output column names from custom query in mysql

I've created a small input form for a custom sql query using php. 我使用php为自定义sql查询创建了一个小的输入表单。 I've been able to output the results to a csv form, however I'm having some trouble including the headers in the output file. 我已经能够将结果输出到csv表单,但是在输出文件中包含标头时遇到了一些麻烦。

I've had no trouble creating an array of the header rows, but I'd like to be able to create the headers out of the query itself. 创建标题行数组没有问题,但是我希望能够从查询本身创建标题。

This is what I've used: 这是我用过的:

$output = fopen('php://output', 'w');


//get query data  

$qs = $_GET['custom'];
$rs  = mysqli_query($dbc, $qs)
  or die ('Error querying database');     


header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=query.csv');

$csv = fopen('php://output', 'w');

while ($row = mysqli_fetch_assoc($rs)) {

    fputcsv($csv, $row);

}

fclose($csv);

What I want is a way of inputting the rows from the select before the content of the query (which comes through fine). 我想要的是一种在查询内容之前输入来自select的行的方法(这很好)。

I know this will work for set headers if I put it in before the first fputcsv line: 我知道如果将它放在第一行fputcsv行之前,它将适用于set头:

fputcsv($csv, array('col1', 'col2', 'col3', [etc...]  ));

but it is only because I define the fields in the array. 但这只是因为我在数组中定义了字段。

What I'm looking for is way to identify the columns in the query and use them as column headers. 我正在寻找的是识别查询中的列并将其用作列标题的方法。

I've been attempting to do something with a query that would just get the column names, and then feed that as an array but I can't seem to get it to work. 我一直在尝试使用仅获取列名的查询来做某事,然后将其作为数组提供,但我似乎无法使其工作。 Something like this: 像这样:

SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'database_name'
and column_name in ($query)

where the $query variable is similar to the $qs query above, but alas no luck. $ query变量与上面的$ qs查询类似,但是可惜没有运气。 Does anyone know how to do this? 有谁知道如何做到这一点? Thanks in advance. 提前致谢。

fputcsv($csv, array_keys($row)); at the beginning? 一开始?

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

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