What potential security risks are present when using foreach loops for SQL queries in PHP?

When using foreach loops for SQL queries in PHP, the main security risk is SQL injection. This can occur if the values from the loop are not properly sanitized before being included in the query, allowing malicious users to manipulate the query and potentially access or modify sensitive data. To mitigate this risk, it is important to use prepared statements with parameterized queries to ensure that user input is properly escaped and sanitized.

// Example of using prepared statements with parameterized queries to prevent SQL injection

$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

foreach($usernames as $username) {
    $stmt->bindParam(':username', $username);
    $stmt->execute();
    
    // Fetch results
}