mysql_field_name Function in PHP

What is mysql_field_name() function in PHP?
How does mysql_field_name works?


mysql_field_name() function returns the name of a field in a resultset.
string mysql_field_name ( resource result, int field_index)

Returns the field name on success, or FALSE on failure.
mysql_field_name() function fetches the name of a specified field in a resultset returned by executing mysql_query() function. The field to be fetched is specified by the field_index value, field_index value ranges from '0' to the number of fields in the recordset
For example if the field_index value is '0', first field name will be fetched, if field_index value is '3', fourth field will be fetched.

// Attempt to connect to the default database server
$link = mysql_connect("mysql_host", "mysql_user", "mysql_password")
or die ("Could not connect");
//select database
$db_select = mysql_selectdb("mydb");
//returns result set on executing the query
$result=mysql_query("select * from employee",$link);
//function returns number of fields in the recordset
$fields_no = mysql_num_fields($result);
$i = 0;
while ($i < $fields_no) {
// return name of the field using mysql_field_name
$name = mysql_field_name ($result, $i);
//display field name
echo "Field name:$name <br>";

In the above example mysql_query() executes simple query and returns recordset, Inorder to display all the field names in the recordset, first mysql_num_fields() function is executed to return number of fields '$fields_no' present in the recordset.
We can loop from '0' till the number of fields '$fields_no' to find all the field names. mysql_field_name function returns field name by passing the recordset and index as the arguments. Index value range from '0' to the number of fields '$fields_no' present in the recordset.
Field name:ID
Field name:Name
Field name:Description

PHP Topics

Ask Questions

Ask Question