mysql_field_len Function in PHP
What is mysql_field_len() function in PHP?
How does mysql_field_len works?
Explanation
mysql_field_len() function returns the maximum length of a field in a recordset.
Syntaxint mysql_field_len ( resource result, int field_offset)
Returns the length of the field on success, or FALSE on failure.
mysql_field_len function will return the length of field associated with each field in the recordset returned by
mysql_query()mysql_field_len function will not return the length of the data stored in the field, it returns the length of the field assigned in the structure of the table. Data stored in that field can be less or equal to the assigned size of that filed.
Example:
<?php // 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",$link); //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); // return field length using mysql_field_len $len = mysql_field_len ($result, $i); //display field name and length of the field echo "Field name:$name--Field Length: $len <br>"; $i++; } ?> |
In the above example
mysql_query() executes simple query and returns recordset, Inorder to display all the field names and size of the field 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 and length of the field.
mysql_field_name() returns field name by passing the recordset and index as the arguments.
mysql_field_len() returns field size of specific field based on the recordset and index value passed. Index value range from '0' to the length of the field '$fields_no'.
RESULT:
Field name:ID --Field Length: 2 Field name:Name--Field Length: 50 Field name:Info--Field Length: 100