How can SQL injection vulnerabilities be avoided when using user input in SQL queries in PHP?

SQL injection vulnerabilities can be avoided by using prepared statements and parameterized queries in PHP. This approach separates the SQL query from the user input, preventing malicious SQL code from being executed.

// Example of using prepared statements to avoid SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

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

// Bind the user input to the parameter
$stmt->bindParam(':username', $userInput);

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

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

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