PHP mysqli: field_count() function

mysqli_field_count() function / mysqli::$field_count

The mysqli_field_count() function / mysqli::$field_count returns the number of columns for the most recent query.


Object oriented style

int $mysqli->field_count;

Procedural style

int mysqli_field_count ( mysqli $link )


Name Description Required/Optional
link A link identifier returned by mysqli_connect() or mysqli_init() Required for procedural style only and Optional for Object oriented style

Usage: Procedural style



Name Description Required/Optional
connection Specifies the MySQL connection to use. Required

Return value:

An integer representing the number of fields in a result set.

Version: PHP 5, PHP 7

Example of object oriented style:

$mysqli = new mysqli("localhost", "user1", "datasoft123", "hr");

$mysqli->query( "DROP TABLE IF EXISTS friends");
$mysqli->query( "CREATE TABLE friends (id int, name varchar(20))");

$mysqli->query( "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

$mysqli->real_query("SELECT * FROM friends");

if ($mysqli->field_count) {
    /* this was a select/show or describe query */
    $result = $mysqli->store_result();

    /* process resultset */
    $row = $result->fetch_row();

    /* free resultset */

/* close connection */

Example of procedural style:


$link = mysqli_connect("localhost", "user1", "datasoft123", "hr");

mysqli_query($link, "DROP TABLE IF EXISTS friends");
mysqli_query($link, "CREATE TABLE friends (id int, name varchar(20))");

mysqli_query($link, "INSERT INTO friends VALUES (1,'Hartmut'), (2, 'Ulf')");

mysqli_real_query($link, "SELECT * FROM friends");

if (mysqli_field_count($link)) {
    /* this was a select/show or describe query */
    $result = mysqli_store_result($link);

    /* process resultset */
    $row = mysqli_fetch_row($result);

    /* free resultset */

/* close connection */



// Check connection
if (mysqli_connect_errno())
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

mysqli_query($con,"SELECT * FROM employees");
// Get number of columns - will always return 3
$count = mysqli_field_count($con);
echo $count;


Sample Output:


See also

PHP Function Reference

Previous: error
Next: get_charset

Follow us on Facebook and Twitter for latest update.