What best practices should be followed when handling exceptions and errors in PHP code related to database operations?
When handling exceptions and errors in PHP code related to database operations, it is important to use try-catch blocks to catch any potential errors that may occur during database interactions. This allows for graceful error handling and prevents the script from crashing unexpectedly. Additionally, it is recommended to log any errors that are caught to aid in debugging and troubleshooting.
try {
// Database connection code
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Database query code
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $userId);
$stmt->execute();
// Fetching results
$user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
// Log the error
error_log('Database error: ' . $e->getMessage());
// Handle the error gracefully
echo 'An error occurred while fetching user data.';
}