Databases 3 min read

How to Get the Number of Rows in a MySQL Result Set Using PHP's mysqli_num_rows

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

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Get the Number of Rows in a MySQL Result Set Using PHP's mysqli_num_rows

When working with PHP to perform database operations, you may need to obtain the number of rows returned by a query. PHP provides the convenient function mysqli_num_rows for this purpose.

Below is a sample code demonstrating how to use mysqli_num_rows to get the row count of 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, the script connects to the database, runs a SELECT statement, stores the result in $result , then calls mysqli_num_rows to obtain the count, storing it in $num_rows , and finally echoes the count.

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

Summary

Using PHP's mysqli_num_rows function makes it easy to determine the number of rows in a result set, which is useful for checking whether data was returned and for counting query results.

backendDatabaseMySQLphpmysqli_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.