How can prepared statements be utilized in PDO to prevent SQL injection vulnerabilities?

Prepared statements in PDO can prevent SQL injection vulnerabilities by separating SQL logic from user input. This means that user input is treated as data rather than executable code, making it impossible for an attacker to inject malicious SQL queries.

// Example of using prepared statements in PDO to prevent SQL injection

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

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

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