What are the benefits of using num_rows to check for the number of results in a MySQL query in PHP?
Using num_rows to check for the number of results in a MySQL query in PHP is beneficial because it allows you to easily determine the number of rows returned by the query, which can be useful for various purposes such as displaying the number of search results or validating the existence of a specific record. This function helps in efficiently handling the result set and making decisions based on the number of rows returned.
// Perform a MySQL query
$query = "SELECT * FROM table_name WHERE condition";
$result = $mysqli->query($query);
// Check the number of rows returned
if ($result->num_rows > 0) {
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with each row
}
} else {
echo "No results found.";
}
// Free the result set
$result->free();