In the PHP code provided, what are the best practices for handling database connections and query results?
When handling database connections and query results in PHP, it is best practice to use exception handling to catch any potential errors that may occur during the database operations. This ensures that any issues are properly handled and does not expose sensitive information to the user. Additionally, it is recommended to use prepared statements when executing queries to prevent SQL injection attacks.
<?php
// 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("Error connecting to the database: " . $e->getMessage());
}
// Prepare and execute a query
try {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(array(':id' => 1));
$result = $stmt->fetch(PDO::FETCH_ASSOC);
// Process the query result
print_r($result);
} catch (PDOException $e) {
die("Error executing query: " . $e->getMessage());
}
// Close the database connection
$pdo = null;
?>