What are some best practices for handling query results in PHP to avoid confusion and errors?

When handling query results in PHP, it's important to check if the query was successful and if there are any results before trying to access the data. This helps avoid errors and confusion when dealing with empty or invalid results. One common approach is to use conditional statements to verify the query result before proceeding with data processing.

// Execute the query
$result = mysqli_query($conn, "SELECT * FROM table");

// Check if the query was successful
if($result){
    // Check if there are any results
    if(mysqli_num_rows($result) > 0){
        // Process the query results
        while($row = mysqli_fetch_assoc($result)){
            // Access and use the data from the query results
            echo $row['column_name'] . "<br>";
        }
    } else {
        echo "No results found.";
    }
} else {
    echo "Error executing query: " . mysqli_error($conn);
}