What are the best practices for logging MySQL errors in PHP?

Logging MySQL errors in PHP is essential for debugging and troubleshooting issues with database queries. One of the best practices is to use the try-catch block to catch any exceptions thrown by MySQL queries and then log the error message along with relevant information such as the query itself, timestamp, and user ID if applicable.

try {
    // Your MySQL query code here
} catch (Exception $e) {
    $error_message = $e->getMessage();
    $query = "Your MySQL query";
    $timestamp = date('Y-m-d H:i:s');
    $user_id = $_SESSION['user_id']; // If applicable

    // Log the error message along with other relevant information
    $log_message = "[$timestamp] Error executing query: $query - Error message: $error_message - User ID: $user_id";
    error_log($log_message, 3, 'error.log'); // Log to a file named error.log
}