How can PHP developers improve error handling and debugging when encountering issues with database interactions in their code?
When encountering issues with database interactions in PHP code, developers can improve error handling and debugging by implementing proper error checking and logging mechanisms. One way to do this is by using try-catch blocks to catch exceptions thrown by database operations and logging detailed error messages. Additionally, developers can enable error reporting and display error messages during development to quickly identify and fix issues.
try {
// Database connection code
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Database query code
$stmt = $db->prepare('SELECT * FROM users');
$stmt->execute();
// Fetching results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
// Log error message
error_log('Database error: ' . $e->getMessage());
// Display user-friendly error message
echo 'An error occurred while fetching data from the database.';
}