How can prepared statements be used in PHP to improve security and efficiency in database queries?

Using prepared statements in PHP can improve security and efficiency in database queries by separating the SQL query from the user input, thus preventing SQL injection attacks. Prepared statements also allow for the reuse of the query with different parameters, reducing the overhead of query parsing and execution.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $username);

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

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