How can prepared statements in PDO help prevent SQL injection vulnerabilities in PHP code?

Using prepared statements in PDO can help prevent SQL injection vulnerabilities in PHP code by separating the SQL query from the user input. This means that the input values are treated as data rather than executable SQL code, making it impossible for malicious input to alter the structure of the SQL query. Prepared statements also automatically escape special characters in the input, further reducing the risk of SQL injection attacks.

// Using prepared statements in PDO to prevent SQL injection

// Establish 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', $_POST['username']);

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

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