PHP mysqli_field_count() Function
Definition and Usage
The mysqli_field_count() function is used to get the number of fields (columns) in the result set of the recently executed MySQL query .
Syntax
mysqli_field_count($con)
Parameters
| Sr.No | Parameter & Description |
|---|---|
| 1 |
con(Mandatory) This is an object representing a connection to MySQL Server. |
Return Values
PHP mysqli_field_count() function returns an integer value indicating the number of columns in the result set of the last query. If the last query is not a SELECT query (no result set) this function returns 0.
PHP Version
This function was first introduced in PHP Version 5 and works works in all the later versions.
Example
Following example demonstrates the usage of the mysqli_field_count() function (in procedural style) −
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
//Query to retrieve all the records of the employee table
mysqli_query($con, "Select * from employee");
//Field Count
$count = mysqli_field_count($con);
print("Field Count: ".$count);
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Field Count: 6
Example
In object oriented style the syntax of this function is $con -> field_count;, Where, $con is the connection object −
<?php
//Creating a connection
$con = new mysqli("localhost", "root", "password", "mydb");
//Query to retrieve all the records of the employee table
$con -> query("Select FIRST_NAME, LAST_NAME, AGE from employee");
//Field Count
$count = $con->field_count;
print("Field Count: ".$count);
//Closing the connection
$con -> close();
?>
This will produce following result −
Field Count: 3
Example
Following is another example of the mysqli_field_count() function
<?php
//Creating a connection
$con = mysqli_connect("localhost", "root", "password", "mydb");
print("Field Count: ".mysqli_field_count($con)."\n");
//INSERT Query
mysqli_query($con, "INSERT INTO employee (FIRST_NAME, AGE) VALUES (Archana, 25), (Bhuvan, 29)");
print("Field Count: ".mysqli_field_count($con));
//Closing the connection
mysqli_close($con);
?>
This will produce following result −
Field Count: 0 Field Count: 0
Example
<?php
$connection_mysql = mysqli_connect("localhost","root", "password", "mydb");
if (mysqli_connect_errno($connection_mysql)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connection_mysql,"SELECT * FROM employee");
print(mysqli_field_count($connection_mysql));
mysqli_close($connection_mysql);
?>
This will produce following result −
6