How to Use PHP's mysqli_num_rows to Get the Row Count of a Result Set
This article explains how to use PHP's mysqli_num_rows function to retrieve the number of rows returned by a MySQL query, providing a step‑by‑step example that connects to the database, executes a SELECT statement, checks for errors, and outputs the row count.
When performing database operations with PHP, you often need to know how many rows a query returned; the mysqli_num_rows function makes this straightforward.
Below is a complete example that demonstrates connecting to a MySQL server, executing a SELECT query, and using mysqli_num_rows to obtain the row count:
<?php
// Assume a successful connection to the database
$mysqli = new mysqli('localhost', 'username', 'password', 'database_name');
// Check connection
if ($mysqli->connect_errno) {
echo "连接数据库失败:" . $mysqli->connect_error;
exit();
}
// Execute query
$query = "SELECT * FROM users";
$result = $mysqli->query($query);
// Verify query success
if (!$result) {
echo "查询失败:" . $mysqli->error;
exit();
}
// Get number of rows in the result set
$num_rows = mysqli_num_rows($result);
// Output the count
echo "结果集中的行数为:" . $num_rows;
// Close the connection
$mysqli->close();
?>The script first establishes a connection, runs a SELECT statement, stores the result in $result, then calls mysqli_num_rows($result) to retrieve the count, storing it in $num_rows and finally echoing the value.
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 will return 0.
Using mysqli_num_rows is a practical way to determine whether data was returned and to count rows in PHP‑based backend applications.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
