How can errors be effectively handled when using PDO for database queries in PHP?
When using PDO for database queries in PHP, errors can be effectively handled by setting the error mode to PDO::ERRMODE_EXCEPTION. This will throw exceptions when errors occur, allowing for easier debugging and error handling in your code.
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Perform database queries here
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
Related questions
-
file_get_contents PHP function
-
date validation PHP functions customization
-
PHP coding standards security