PHP Tutorial - PHP mysqli_num_fields() Function






Definition

The mysqli_num_fields() function returns the number of fields (columns) in a result set.

Syntax

PHP mysqli_num_fields() Function has the following syntax.

Object oriented style

int $mysqli_result->field_count;

Procedural style

int mysqli_num_fields ( mysqli_result $result )

Parameter

ParameterIs RequiredDescription
resultRequired.A result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result()

Return

The number of fields from a result set.

Example

The following code returns the number of columns in a result set.


<?php//from  w  ww.java  2s  . c om
$con=mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno($con)){
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT name FROM emp";

if ($result=mysqli_query($con,$sql)){
  // Return the number of fields in result set
  $fieldcount=mysqli_num_fields($result);

  print $fieldcount;

  mysqli_free_result($result);
}

mysqli_close($con);
?>




Example 2


<?php/*from   ww  w. ja  va2s.c om*/
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT * FROM City")) {

    /* determine number of fields in result set */
    $field_cnt = $result->field_count;

    printf("Result set has %d fields.\n", $field_cnt);

    $result->close();
}

$mysqli->close();
?>