In what situations should you use prepared statements or parameterized queries instead of directly inserting variables into SQL queries?

When directly inserting variables into SQL queries, it leaves the application vulnerable to SQL injection attacks. To prevent this, it is recommended to use prepared statements or parameterized queries. Prepared statements separate the SQL query from the user input, making it impossible for an attacker to inject malicious code into the query.

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