What are best practices for handling MySQL queries and results in PHP to avoid errors like "supplied argument is not a valid MySQL result resource"?

When handling MySQL queries in PHP, it's important to check if the query was executed successfully before trying to fetch results. This error often occurs when a query fails, and the result resource is not valid. To avoid this error, you should check if the query was successful and only proceed with fetching results if it was.

// Execute the query
$result = mysqli_query($connection, $query);

// Check if the query was successful
if($result) {
    // Fetch results
    while($row = mysqli_fetch_assoc($result)) {
        // Process the results
    }
} else {
    echo "Error: " . mysqli_error($connection);
}