How can prepared statements be used to prevent SQL injection vulnerabilities in PHP code, as suggested in the forum thread?

SQL injection vulnerabilities occur when user input is directly concatenated into SQL queries, allowing malicious users to manipulate the queries. Prepared statements in PHP can prevent this by separating the SQL query from the user input, ensuring that input is treated as data rather than executable code.

// Establish a 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 prepared statement
$stmt->execute();

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