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

Prepared statements in PDO can help prevent SQL injection vulnerabilities in PHP applications by separating SQL code from user input. By using placeholders for user input in the SQL query and binding the actual values to these placeholders, PDO ensures that user input is treated as data rather than executable code, thus preventing malicious SQL injection attacks.

// Connect to database
$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 actual user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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