How can the use of PDO Prepared Statements improve the security and efficiency of database queries in PHP?

Using PDO Prepared Statements in PHP can improve security by preventing SQL injection attacks, as it automatically escapes special characters in user input. It also improves efficiency by allowing the database to compile the query only once and reuse it multiple times with different parameters, reducing the overhead of parsing and optimizing the query each time it is executed.

// Connect to the database
$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 the parameter values to the placeholders
$stmt->bindParam(':username', $username);

// Execute the prepared statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();