How can using placeholders and passing parameters separately improve the security and efficiency of PHP code?

Using placeholders and passing parameters separately in SQL queries can improve the security and efficiency of PHP code by preventing SQL injection attacks. By using placeholders, the SQL query is precompiled and the parameters are bound separately, ensuring that user input is treated as data and not executable code. This practice also helps optimize query execution as the database can cache the query plan.

// Using placeholders and passing parameters separately in a SQL query
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username, PDO::PARAM_STR);
$stmt->execute();

// Fetch data
while ($row = $stmt->fetch()) {
    // Process data
}