How can the use of placeholders in SQL queries improve security and prevent SQL injection in PHP?

Using placeholders in SQL queries can improve security and prevent SQL injection in PHP by separating the SQL query from the user input. Placeholders act as markers for where the user input should be inserted, and the actual values are bound to these placeholders separately. This prevents malicious SQL code from being directly injected into the query, as the input is treated as data rather than executable code.

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

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

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

// Execute the query
$stmt->execute();

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