How to Count Rows in a MySQL Result Set with PHP’s mysqli_num_rows

Learn how to use PHP’s mysqli_num_rows function to retrieve the number of rows returned by a MySQL query, with a complete example that shows connecting to the database, executing a SELECT statement, handling errors, and outputting the row count.

php Courses
php Courses
php Courses
How to Count Rows in a MySQL Result Set with PHP’s mysqli_num_rows

When performing database operations with PHP, 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 demonstrating how to use mysqli_num_rows to get the row count of a result set:

<?php
// Assume a connection to the database has been established
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');

// Check if the connection succeeded
if ($mysqli->connect_errno) {
    echo "Failed to connect to database: " . $mysqli->connect_error;
    exit();
}

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

// Verify the query succeeded
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);

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

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

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

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 retrieve the number of rows in a result set, which is useful for determining whether data was returned and for counting query results.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

databaseMySQLiRow 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

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.