Backend Development 3 min read

How to Use mysqli_num_rows in PHP to Get the Number of Rows in a Result Set

This article explains how to use PHP's mysqli_num_rows function to retrieve the row count from a MySQL result set, provides a complete example with connection handling, query execution, error checking, and demonstrates proper usage and limitations of the function.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use mysqli_num_rows in PHP to Get the Number of Rows in a Result Set

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

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

connect_errno) {
    echo "Failed to connect to database: " . $mysqli->connect_error;
    exit();
}

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

// Verify that the query executed successfully
if (!$result) {
    echo "Query failed: " . $mysqli->error;
    exit();
}

// Use mysqli_num_rows to get the number of rows in the result set
$num_rows = mysqli_num_rows($result);

// Output the result
echo "Number of rows in the result set: " . $num_rows;

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

In the example, we first connect to the database, execute a SELECT query, and store the result set in the $result variable. We then call mysqli_num_rows to obtain the row count, store it in $num_rows , and finally echo the count.

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

Summary

Using the PHP function mysqli_num_rows provides an easy way to determine the number of rows returned by a query, which is useful for checking whether data was retrieved and for counting query results.

PHP Beginner Tutorial: Learn PHP in One Week

Scan the QR code to receive learning materials for free

Databasebackend developmentPHPmysqliRow Count
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.