How can SQL injection vulnerabilities be prevented in PHP code, especially when dealing with user input?

SQL injection vulnerabilities can be prevented in PHP code by using prepared statements with parameterized queries when interacting with a database. This approach separates the SQL query logic from the user input data, preventing malicious SQL code from being executed. Additionally, input validation and sanitization can help ensure that only expected data is passed to the database queries.

// Example of preventing SQL injection using prepared statements

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

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

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

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

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

// Process the results as needed
foreach ($results as $row) {
    // Do something with the data
}