472,145 Members | 1,614 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,145 software developers and data experts.

Getting column names from MySQL query result

170 100+
I picked up the following code to take a mysql table to an excel file. What do I need to do to it to make the first excel row be the column names, rather than the first record?
Expand|Select|Wrap|Line Numbers
  1. $query  = "SELECT * FROM mytable";
  2. $result = mysql_query($query) or die('Error, query failed');
  3.  
  4. $tsv  = array();
  5.  
  6. while($row = mysql_fetch_array($result, MYSQL_NUM))
  7. {
  8.    $tsv[]  = implode("\t", $row);
  9. }
  10.  
  11. $tsv = implode("\r\n", $tsv);
  12.  
  13. $fileName = 'file.xls';
  14. header("Content-type: application/vnd.ms-excel");
  15. header("Content-Disposition: attachment; filename=$fileName");
  16.  
  17. echo $tsv;
  18.  
Mar 31 '07 #1
3 13443
ronverdonk
4,258 Expert 4TB
When you want to show the column names of your result, you have to use the mysql_field_name command. The following code snippet shows you how to display the column names of the result onmto the screen.

You can adapt it to your own choosing.

[php]
if (mysql_num_rows($result) > 0) {
$numfields = mysql_num_fields($result);
for ($i=0; $i < $numfields; $i++)
echo mysql_field_name($result, $i).'</br>';
}[/php]

Ronald :cool:
Mar 31 '07 #2
beary
170 100+
Thanks Ronald.

When you want to show the column names of your result, you have to use the mysql_field_name command. The following code snippet shows you how to display the column names of the result onmto the screen.

You can adapt it to your own choosing.

[php]
if (mysql_num_rows($result) > 0) {
$numfields = mysql_num_fields($result);
for ($i=0; $i < $numfields; $i++)
echo mysql_field_name($result, $i).'</br>';
}[/php]

Ronald :cool:
Apr 1 '07 #3
ronverdonk
4,258 Expert 4TB
You are welcome. See you next time.

Ronald :cool:
Apr 1 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

2 posts views Thread by kindermaxiz | last post: by
4 posts views Thread by ChronoFish | last post: by
2 posts views Thread by Joe Gazda | last post: by
4 posts views Thread by rass.elma | last post: by
reply views Thread by Saiars | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.