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 number of rows in a MySQL result set, providing a complete example that connects to a database, executes a query, checks for errors, obtains the row count, and outputs it.
When performing database operations with PHP, you may need to know how many rows a query returned. PHP provides the convenient function mysqli_num_rows for this purpose.
Below is a sample code demonstrating how to use mysqli_num_rows to obtain the row count of a result set:
<?php
// Assume a connection to the database has already 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 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();
?>The example first establishes a connection to the database, then runs a SELECT query and stores the result in $result . It then calls mysqli_num_rows($result) to obtain the row count, stores it in $num_rows , and echoes the value.
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 determine the number of rows in a result set, which is useful for checking whether data was returned and for counting query results.
Java learning materials
C language learning materials
Frontend learning materials
C++ learning materials
PHP learning materials
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.