简体   繁体   中英

output column names from custom query in mysql

I've created a small input form for a custom sql query using php. 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.

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).

I know this will work for set headers if I put it in before the first fputcsv line:

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. Does anyone know how to do this? Thanks in advance.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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