How can improper handling of SQL queries in PHP code lead to security vulnerabilities like SQL injection?

Improper handling of SQL queries in PHP code can lead to security vulnerabilities like SQL injection because it allows malicious users to manipulate the SQL query by injecting additional SQL code. To prevent this, developers should use parameterized queries or prepared statements, which separate the SQL query logic from the user input, making it impossible for attackers to inject malicious code.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();