SQL PHP HTML ASP JavaScript articles and free scripts to download
 

mysql_field_name Functions to get name of the fields of a table

The function mysql_field_name returns the name of the filed 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


Discuss this tutorial at forum

List of SQL Tutorials


Scripts
PHP
JavaScript
SQL Tutorial List
SQL (Home)
mysql_affected_rows mysql_change_user mysql_close mysql_connect mysql_create_db mysql_data_seek mysql_db_name mysql_db_query mysql_drop_db mysql_errno mysql_error mysql_fetch_array mysql_fetch_assoc mysql_fetch_field mysql_fetch_lengths mysql_fetch_row mysql_field_flags mysql_field_len mysql_field_name mysql_field_seek mysql_field_table mysql_field_type mysql_free_result mysql_insert_id mysql_list_dbs mysql_list_fields mysql_list_tables mysql_num_fields mysql_num_rows mysql_pconnect mysql_query mysql_result mysql_select_db mysql_tablename
SQL site Map
Knowledge Management
Subscribe
Submit your email address and receive article and product notifications. Your email is safe with us.