By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,930 Members | 1,492 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,930 IT Pros & Developers. It's quick & easy.

Getting column names from MySQL query result

100+
P: 170
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
Share this Question
Share on Google+
3 Replies


ronverdonk
Expert 2.5K+
P: 4,258
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

100+
P: 170
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
Expert 2.5K+
P: 4,258
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.