What best practices should be followed when handling MySQL errors in PHP code to effectively troubleshoot issues like invalid result resources?

When handling MySQL errors in PHP code, it is important to check for errors after executing queries and handle them appropriately. To troubleshoot issues like invalid result resources, you can use functions like mysqli_error() to get detailed error messages and mysqli_errno() to get the error number. Additionally, always check if the query was successful before trying to fetch results from the result resource.

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

// Check for errors
if (!$result) {
    echo "Error: " . mysqli_error($connection);
    echo "Error number: " . mysqli_errno($connection);
} else {
    // Fetch results from the result resource
    while ($row = mysqli_fetch_assoc($result)) {
        // Process the results
    }
}