mysql_field_type Function in PHP

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

Explanation

mysql_field_type() function returns the type of a field in a result set.
Syntax
string mysql_field_type ( resource result, int field_offset)

Returns the specified field type on success, or FALSE on failure.
mysql_field_type function will return the type of the specified field in the record set. Some of the field types are varchar, char, int, blob, text, datetime etc
In the below code result set returned by mysql_query() and field index is passed as an arguments to mysql_field_type to display data type of field specified by field index. Here data type of particular field is displayed.
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 user",$link);
// return specified field type
$type = mysql_field_type($result, 0);
//display field type
echo "Field type:$type <br>";
?>

You can also loop through the result set to display the data type of all the fields present in the result set.
RESULT:
Field type:Int
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 user",$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 type using mysql_field_type
$type = mysql_field_type ($result, $i);
//display field name and data type of the field
echo "Field name:$name--Field Type: $type <br>";
$i++;
}
?>
RESULT:
Field name:ID --Field Type: Int
Field name:Name--Field Type: String
Field name:Info--Field Type: String

PHP Topics


Ask Questions

Ask Question