How to Use PHP mysqli_num_rows to Get the Number of Rows in a Result Set
This article demonstrates 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, executes a SELECT statement, checks for errors, obtains the row count, and outputs the result.
When working with databases in PHP, you may need to know how many rows a query returned; the mysqli_num_rows function provides a convenient way to obtain this count.
connect_errno) {
echo "Failed to connect to database: " . $mysqli->connect_error;
exit;
}
// Execute a query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
// Verify query success
if (!$result) {
echo "Query failed: " . $mysqli->error;
exit;
}
// Get number of rows in result set
$num_rows = mysqli_num_rows($result);
// Output the count
echo "Number of rows in result set: " . $num_rows;
// Close the connection
$mysqli->close();
?>In the example, the script connects to the MySQL server, runs a SELECT statement, checks for errors, uses mysqli_num_rows to retrieve the row count stored in $num_rows , and echoes the result.
Note that mysqli_num_rows should only be called after a successful query; if the query fails, the result set is empty and the function returns 0.
Using mysqli_num_rows is a practical technique for determining whether data was returned and for counting rows in database operations.
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.