When using PHP to operate a MySQL database, we often need to know how many rows of data a query statement returns. This is particularly common in scenarios such as paging and data verification. This article will introduce how to get the number of rows of the query result through the mysqli_result::num_rows method.
mysqli_result::num_rows is an object-oriented property that gets the number of rows in the query result set. It can only be used for SELECT queries and is used when the query is successful and data is included in the result set.
$result->num_rows;
where $result is the mysqli_result object returned after mysqli::query() is executed.
Here is a simple PHP example that demonstrates how to use mysqli_result::num_rows to get the number of rows for query results:
<?php
// Database connection configuration
$host = 'localhost';
$user = 'root';
$password = 'your_password';
$database = 'test_db';
// Create a database connection
$mysqli = new mysqli($host, $user, $password, $database);
// Check if the connection is successful
if ($mysqli->connect_error) {
die('Connection failed: ' . $mysqli->connect_error);
}
// Define query statements
$sql = "SELECT * FROM users WHERE status = 'active'";
// Execute a query
$result = $mysqli->query($sql);
// Check whether the query is successful
if ($result) {
// Get the number of rows
echo "There are a total of " . $result->num_rows . " Activate users。";
// Release the result set
$result->free();
} else {
echo "There was an error in query: " . $mysqli->error;
}
// Close the database connection
$mysqli->close();
?>
num_rows can only be used for SELECT type queries and is invalid for INSERT , UPDATE , or DELETE .
If you are using mysqli::store_result() to get the result set, you can also get the number of rows through num_rows .
If the data volume is large, it is recommended to use the SQL statement SELECT COUNT(*) to count the total number of rows to improve performance.
PHP official document: https://www.php.net/manual/zh/mysqli-result.num-rows.php
Example online demonstration address: https://m66.net/demo/num_rows_example
Through the introduction of this article, I believe you have mastered how to obtain the number of rows of MySQL query results through mysqli_result::num_rows . In daily development, making good use of this attribute can help you process data more efficiently.
Do you want to know other common methods of mysqli?