What are some best practices for handling database queries in PHP to avoid errors like missing database entries?

When handling database queries in PHP, one best practice to avoid errors like missing database entries is to always check if the query returned any results before trying to access them. This can be done by checking the number of rows returned by the query and handling the case where no rows are found gracefully.

// Execute the database query
$result = mysqli_query($connection, "SELECT * FROM table WHERE condition");

// Check if any rows were returned
if(mysqli_num_rows($result) > 0) {
    // Fetch and process the results
    while($row = mysqli_fetch_assoc($result)) {
        // Access and use the data from the database
    }
} else {
    // Handle the case where no rows are found
    echo "No results found.";
}