Backend Development 3 min read

How to Use PHP's mysqli_num_rows to Get the Row Count of a Result Set

This article explains how to use PHP's mysqli_num_rows function to retrieve the number of rows returned by a MySQL query, providing a step‑by‑step example that connects to the database, executes a SELECT statement, checks for errors, and outputs the row count.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP's mysqli_num_rows to Get the Row Count of a Result Set

When performing database operations with PHP, you often need to know how many rows a query returned; the mysqli_num_rows function makes this straightforward.

Below is a complete example that demonstrates connecting to a MySQL server, executing a SELECT query, and using mysqli_num_rows to obtain the row count:

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

// Execute query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

// Verify query success
if (!$result) {
    echo "查询失败:" . $mysqli->error;
    exit();
}

// Get number of rows in the result set
$num_rows = mysqli_num_rows($result);

// Output the count
echo "结果集中的行数为:" . $num_rows;

// Close the connection
$mysqli->close();
?>

The script first establishes a connection, runs a SELECT statement, stores the result in $result , then calls mysqli_num_rows($result) to retrieve the count, storing it in $num_rows and finally echoing the value.

Note that mysqli_num_rows should only be called after a successful query; if the query fails, the result set is empty and the function will return 0.

Using mysqli_num_rows is a practical way to determine whether data was returned and to count rows in PHP‑based backend applications.

Databasebackend developmentMySQLPHPmysqli
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.