What are the potential pitfalls of using variables directly in SQL queries in PHP?

Using variables directly in SQL queries in PHP can lead to SQL injection attacks, where malicious SQL code is inserted into the query. To prevent this, you should use prepared statements with placeholders for variables in your SQL queries. This way, the variables are bound to the placeholders separately, preventing any injected SQL code from being executed.

// 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->bindParam(':username', $username);
$stmt->execute();