What potential security risks are associated with directly inserting user input into SQL queries in PHP?

Directly inserting user input into SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unauthorized SQL commands. To prevent this, it is essential to use parameterized queries or prepared statements, which separate the SQL query logic from the user input data, thereby preventing SQL injection attacks.

// Using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $_POST['username']]);
$results = $stmt->fetchAll();
foreach ($results as $row) {
    // Process the results
}