How can the code be improved to handle errors and exceptions more effectively in the context of database operations?
When performing database operations in PHP, it's important to handle errors and exceptions effectively to prevent unexpected behavior or security vulnerabilities. One way to improve error handling is to use try-catch blocks to catch exceptions and handle them gracefully, providing informative error messages to the user or logging them for debugging purposes.
try {
$conn = new PDO("mysql:host=localhost;dbname=myDB", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database operations here
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
// Log the error to a file or error tracking system
}