mysqli_num_rows PHP Function: Usage Guide
The mysqli_num_rows function in PHP is used to retrieve the number of rows in a MySQL query result. It takes a MySQLi result object as a parameter and returns the number of rows in the result set.
The syntax of the function is as follows:
mysqli_num_rows(mysqli_result $result): int|false
$result is a MySQLi result object which can be obtained by executing an SQL query and using the mysqli_query function. The function will return an integer value indicating the number of rows in the result set, or return false if an error occurs.
Here is an example demonstrating how to use the mysqli_num_rows function to get the number of rows in a query result.
// 连接到数据库
$connection = mysqli_connect("localhost", "username", "password", "database");
// 执行查询
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// 获取行数
if ($result) {
$numRows = mysqli_num_rows($result);
echo "查询到 {$numRows} 行数据";
} else {
echo "查询失败";
}
// 关闭连接
mysqli_close($connection);
By using the mysqli_num_rows function, we can easily obtain the number of rows in the query result and process it accordingly. This is very useful for determining if the query result is empty or calculating the number of rows in the result set.