How to Quickly Get Row Count in PHP MySQLi Queries with mysqli_num_rows

This guide shows how to use PHP's mysqli_num_rows function to retrieve the number of rows returned by a MySQL query, including a complete example that connects to the database, runs a SELECT statement, checks for errors, obtains the row count, and closes the connection.

php Courses
php Courses
php Courses
How to Quickly Get Row Count in PHP MySQLi Queries with mysqli_num_rows

When working with PHP and MySQL, you may need to know how many rows a query returned. PHP provides the convenient mysqli_num_rows function for this purpose.

Below is a complete example demonstrating how to use mysqli_num_rows to obtain the row count from a result set:

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

// Check if the connection was successful
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);

// 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 in $result. Then we call mysqli_num_rows($result) to retrieve the row count and store it in $num_rows. Finally, we echo the count to the page.

Note that mysqli_num_rows should only be used after a query has executed successfully; if the query fails, the result set contains no data and the function will return 0.

Summary

Using PHP's mysqli_num_rows function makes it easy to obtain 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.

PHPMySQLiRow 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

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.