MySQLi Tutorial MySQLi References

mysqli_result $num_rows Property



The mysqli_result::$num_rows / mysqli_num_rows() function is used to get the number of rows in the result set.

The behavior of mysqli_num_rows() depends on whether buffered or unbuffered result sets are being used. This function returns 0 for unbuffered result sets unless all rows have been fetched from the server.

Syntax

//Object-oriented style
$mysqli_result->num_rows;

//Procedural style
mysqli_num_rows(result)

Parameters

result Required. For procedural style only: Specify a mysqli_result object returned by mysqli_query(), mysqli_store_result(), mysqli_use_result() or mysqli_stmt_get_result().

Return Value

Returns an int representing the number of fetched rows. Returns 0 in unbuffered mode unless all rows have been fetched from the server.

Note: If the number of rows is greater than PHP_INT_MAX, the number will be returned as a string.

Example: Object-oriented style

The example below shows the usage of mysqli_result::$num_rows 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();
}

//getting query result from the database
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
$result = $mysqli->query($sql);

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

//getting the number of rows in the result set
$row_cnt = $result->num_rows;
printf("Result set has %d rows.\n", $row_cnt);
?>

The output of the above code will be similar to:

Result set has 58 rows.

Example: Procedural style

The example below shows the usage of mysqli_num_rows() 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();
}

//getting query result from the database
$sql = "SELECT EmpID, Name, Age FROM Employee ORDER BY Age";
$result = mysqli_query($mysqli, $sql);

//closing the connection
mysqli_close($mysqli);

//getting the number of rows in the result set
$row_cnt = mysqli_num_rows($result);
printf("Result set has %d rows.\n", $row_cnt);
?>

The output of the above code will be similar to:

Result set has 58 rows.

❮ MySQLi Functions Reference