How can error handling be improved in PHP scripts that interact with a database?
Error handling in PHP scripts that interact with a database can be improved by using try-catch blocks to catch and handle exceptions that may occur during database operations. This allows for more graceful handling of errors and prevents the script from crashing unexpectedly.
try {
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Perform database operations
$stmt = $pdo->prepare('SELECT * FROM users');
$stmt->execute();
// Fetch results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close the database connection
$pdo = null;
} catch (PDOException $e) {
// Handle any database errors
echo 'Error: ' . $e->getMessage();
}