How can the code be improved to handle errors more effectively, especially in the database queries?
To handle errors more effectively, especially in database queries, we can use try-catch blocks to catch any exceptions that may occur during the query execution. By catching these exceptions, we can handle errors gracefully and provide meaningful error messages to the user.
try {
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if(!$user) {
throw new Exception("User not found");
}
// Process user data
} catch(PDOException $e) {
echo "Database error: " . $e->getMessage();
} catch(Exception $e) {
echo "Error: " . $e->getMessage();
}