What common errors can occur when using variables $sql and $statement in PHP?

One common error that can occur when using variables $sql and $statement in PHP is not properly preparing and executing the SQL statement, which can lead to SQL injection vulnerabilities. To solve this issue, it is important to use prepared statements with placeholders for user input in the SQL query.

// Incorrect way without prepared statements
$sql = "SELECT * FROM users WHERE username = '$username'";
$statement = $pdo->query($sql);

// Correct way using prepared statements
$sql = "SELECT * FROM users WHERE username = :username";
$statement = $pdo->prepare($sql);
$statement->bindParam(':username', $username);
$statement->execute();