How can SQL injection vulnerabilities be prevented in PHP code, specifically when handling user input like in the provided example?

SQL injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries instead of directly concatenating user input into SQL queries. This approach separates the SQL query logic from the user input data, preventing malicious SQL code from being injected.

// Using prepared statements with parameterized queries to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// User input
$user_input = $_POST['user_input'];

// Prepare a SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind parameters
$stmt->bindParam(':username', $user_input);

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}