w3resource

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.

Syntax:

Object oriented style

int $mysqli->field_count;

Procedural style

int mysqli_field_count ( mysqli $link )

Parameter:

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

mysqli_field_count(connection);

Parameter:

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:

<?php
$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 */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

Example of procedural style:

<?php

$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 */
    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);

?>

Example:

<?php
$con=mysqli_connect("localhost","user1","datasoft123","hr");
// 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;

mysqli_close($con);
?>

Sample Output:

11

See also

PHP Function Reference

Previous: error
Next: get_charset



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/php/function-reference/mysqli_field_count.php