What are some best practices for handling database queries in PHP 7 using PDO?
When handling database queries in PHP 7 using PDO, it is important to use prepared statements to prevent SQL injection attacks and ensure data security. Additionally, it is recommended to use try-catch blocks to handle exceptions and errors gracefully. Finally, always remember to close the database connection after executing queries to free up resources.
<?php
// Establish database connection
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';
try {
$pdo = new PDO($dsn, $username, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Error: " . $e->getMessage());
}
// Prepare and execute a query using a prepared statement
try {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
// Close the database connection
$pdo = null;
?>