How can prepared statements and PDO be utilized in PHP to improve database query security and performance?
When executing database queries in PHP, using prepared statements with PDO can improve security by preventing SQL injection attacks and also enhance performance by caching the query plan. Prepared statements allow you to separate SQL logic from data input, reducing the risk of malicious input affecting the query execution.
// Establish a database connection using PDO
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare a SQL statement with placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
// Bind parameters to the placeholders
$stmt->bindParam(':username', $username);
// Execute the prepared statement
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll();