Databases 3 min read

How to Use PHP mysqli_num_rows to Get Row Count from a Result Set

This article explains how to retrieve the number of rows in a MySQL result set using PHP's mysqli_num_rows function, providing a complete example that connects to a database, executes a SELECT query, checks for errors, obtains the row count, and displays it.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP mysqli_num_rows to Get Row Count from a Result Set

When performing database operations with PHP, you may need to obtain the number of rows in a query result set; PHP provides the convenient mysqli_num_rows function for this purpose.

Below is a complete example that demonstrates how to use mysqli_num_rows to retrieve the row count from a result set:

connect_errno) {
    echo "连接数据库失败:" . $mysqli->connect_error;
    exit();
}

// 执行查询语句
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

// 检查查询语句是否执行成功
if (!$result) {
    echo "查询失败:" . $mysqli->error;
    exit();
}

// 使用 mysqli_num_rows 函数获取结果集中的行数
$num_rows = mysqli_num_rows($result);

// 打印结果
echo "结果集中的行数为:" . $num_rows;

// 关闭数据库连接
$mysqli->close();
?>

In the example, the script first establishes a connection to the database, runs a SELECT * FROM users query, stores the result in $result , then calls mysqli_num_rows($result) to get the number of rows, stores it in $num_rows , and finally echoes the count.

Note that mysqli_num_rows can only be used after a successful query; if the query fails, the result set contains no data and the function returns 0.

Summary

Using PHP's mysqli_num_rows function makes it easy to obtain the row count of a result set, which is useful for determining whether data was returned and for counting query results.

PHP8 video tutorial

Scan the QR code to receive free learning materials

DatabasePHPmysqliRow Countmysqli_num_rows
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.