How to get a list of column names from sql query

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Azhrarn
Forum Newbie
Posts: 12
Joined: Mon Dec 15, 2003 4:32 am

How to get a list of column names from sql query

Post by Azhrarn »

Heya,
I know its a stupid question, but how would I list out all the column names I got from an sql query?
I need for instance
<name of column> <value of column>
ie
computer_name computer-1
computer_name computer-2
computer_name computer-3

Thanks!
Azh
jolan_lars
Forum Newbie
Posts: 19
Joined: Thu Oct 23, 2003 12:15 pm

Post by jolan_lars »

if your using mysql, u can use:

mysql_field_name( resource result, field index);

eg.

$res = mysql_query("select computer_name from computers");
echo mysql_field_name($res, 0); //prints column name

$field=mysql_fetch_row($res);
echo $field[0];//prints column value
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

Assuming that you used MySQL, if you've returned the result as an associative array (using [php_man]mysql_fetch_assoc[/php_man]()), you could do:

Code: Select all

while ($row = mysql_fetch_assoc($result)) {
    foreach ($row as $column_name => $column_value) {
        echo $column_name.' '.$column_value.'<br />';
    }
}
That's one way.

Mac
Azhrarn
Forum Newbie
Posts: 12
Joined: Mon Dec 15, 2003 4:32 am

Post by Azhrarn »

thanks guys!
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Look here. It's almost exactly what you're asking for (I think).

http://ca.php.net/manual/en/function.my ... fields.php
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply