What are the best practices for handling empty query results in PHP when fetching data from a database?

When fetching data from a database in PHP, it is common to encounter empty query results. To handle this situation gracefully, you can check if the result set is empty before attempting to access any data. This can be done by checking the number of rows returned by the query. If the result set is empty, you can display a message to the user indicating that no data was found.

// Fetch data from the database
$query = "SELECT * FROM table_name WHERE condition";
$result = mysqli_query($connection, $query);

// Check if the result set is empty
if(mysqli_num_rows($result) == 0) {
    echo "No data found.";
} else {
    // Process the data
    while($row = mysqli_fetch_assoc($result)) {
        // Display or use the fetched data
    }
}