PHP Function Reference

PHP mysqli $field_count Property



The PHP mysqli::$field_count / mysqli_field_count() function returns the number of columns for the most recent query on the connection represented by the mysql parameter. This function can be useful when using the mysqli_store_result() function to determine if the query should have produced a non-empty result set or not without knowing the nature of the query.

Syntax

//Object-oriented style
$mysqli->field_count;

//Procedural style
mysqli_field_count(mysql)

Parameters

mysql Required. For procedural style only: Specify a mysqli object returned by mysqli_connect() or mysqli_init().

Return Value

Returns an integer representing the number of fields in a result set.

Example: Object-oriented style

The example below shows the usage of mysqli::$field_count property.

<?php
//establishing connection to the database
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: ". $mysqli->connect_error;
  exit();
}

//executing an SQL query
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
$mysqli->real_query($sql);

if ($mysqli->field_count) {
  //transferring the result set from the last query
  $result = $mysqli->store_result();

  //processing the resultset
  $row = $result->fetch_row();

  //free the memory associated with the result
  $result->close();
}

//closing the connection
$mysqli->close();
?>

Example: Procedural style

The example below shows the usage of mysqli_field_count() function.

<?php
//establishing connection to the database
$mysqli = mysqli_connect("localhost", "user", "password", "database");
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: ". mysqli_connect_error();
  exit();
}

//executing an SQL query
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
mysqli_real_query($mysqli, $sql);

if (mysqli_field_count($mysqli)) {
  //transferring the result set from the last query
  $result = mysqli_store_result($mysqli);

  //processing the resultset
  $row = mysqli_fetch_row($result);

  //free the memory associated with the result
  mysqli_free_result($result);
}

//closing the connection
mysqli_close($mysqli);
?>

❮ PHP MySQLi Reference