What best practices should be followed when handling database connection and query errors in PHP?
When handling database connection and query errors in PHP, it is important to check for errors after each database operation and handle them appropriately to prevent potential security vulnerabilities and improve user experience. This can be done by using try-catch blocks to catch exceptions, logging errors for debugging purposes, and displaying user-friendly error messages when necessary.
// Establish database connection
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
// Perform database query
try {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
$result = $stmt->fetch();
} catch (PDOException $e) {
error_log("Query failed: " . $e->getMessage());
die("An error occurred while fetching data.");
}
// Display query results
if ($result) {
echo "User ID: " . $result['id'] . "<br>";
echo "Username: " . $result['username'];
} else {
echo "No user found.";
}