How can error handling be improved in the PHP code snippet provided to better identify issues with data retrieval from a MySQL database?
The issue with the current PHP code snippet is that it lacks proper error handling for data retrieval from a MySQL database. To improve error handling and better identify issues with data retrieval, we can use try-catch blocks to catch and handle any exceptions that may occur during the database query execution.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM table");
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Process the retrieved data here
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>