What are the best practices for handling MySQL errors in PHP applications to ensure smooth functionality and user experience?

When handling MySQL errors in PHP applications, it is crucial to implement error handling to ensure smooth functionality and provide a better user experience. One common practice is to use try-catch blocks to catch exceptions thrown by MySQL queries and handle them appropriately. Additionally, logging errors to a file or database can help in troubleshooting and identifying issues quickly.

try {
    // MySQL connection code
    $conn = new mysqli($servername, $username, $password, $dbname);
    
    // MySQL query execution
    $result = $conn->query($sql);
    
    if (!$result) {
        throw new Exception($conn->error);
    }
    
    // Process the result
    
} catch (Exception $e) {
    // Handle the error
    error_log("MySQL Error: " . $e->getMessage());
    
    // Display a user-friendly error message
    echo "An error occurred. Please try again later.";
}