SQL PHP HTML ASP JavaScript articles and free scripts to download If you are facing any problem in viewing this page, please tell us
 

mysql_field_name Functions to get name of the fields of a table


The function mysql_field_name returns the name of the field we supply as field index. For example let us use one simple table student where we have four columns ID, name, class & mark. These four columns name we have specified while creating or modifying the table. We can get these table names by using mysql_field_name function.

Here is the syntax

mysql_field_name ( $result , int $field_index )

As you have seen this function takes two inputs, one is the result of a mysql_query() function, the other one is the index of the field. The index of the first field is 0 ( zero ) and for second field it is 1. So if we want the header ( column name ) of fourth field then we have to use 3 as index in the mysql_field_name.

If we don't know the index of the field or don't know how many fields are there in a table then we can use mysql_num_fields function. Once we know the total number of fields in a table then we can use them as field index to get the field name.

Here is the code for displaying the field names of any table. ( It is assumed that you have active connection to mysql and database selection is done )

$q=mysql_query("select * from student order by id ");
$num_fields = mysql_num_fields($q);

echo "<table><tr>";

for ($i=0; $i < $num_fields; $i++)
{ echo '<th>'.mysql_field_name($q, $i).'</th>'; }

echo "</tr></table>";



The output of the above code is here for our student table.

id name class mark

Now let us add data also here and display all the records along with the table headers , here is the full code.

$q=mysql_query("select * from student order by id ");
$num_fields = mysql_num_fields($q);

echo "<table><tr>";

////Field name display starts////
for ($i=0; $i < $num_fields; $i++)
{ echo '<th>'.mysql_field_name($q, $i).'</th>'; }
/// Field name display ends /////

/// Data or Record display starts /////
while($nt=mysql_fetch_row($q)){
echo "<tr >";
while (list ($key, $val) = each ($nt)){echo "<td>$val</td>";}
echo "</tr>";
}
////// End of data display ///////
echo "</tr></table>";

Download sql dump of student table

Not known28-11-2009
The above code duplicates the value for each cell. Any fix?
smo15-01-2010
Above code works perfectly. No problem.
Post Comment This is for short comments only. Use the forum for more discussions.
Name
Email( not to be displayed)Privacy Policy
1+2=This is to prevent automatic submission by spammers. Please enter the result of the sum as asked
Sections
PHP
JavaScript
ASP
HTML
SQL
Photoshop
Articles SEO
SQL Tutorial List
SQL site Map
Knowledge Management
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.