What are some common errors or mistakes to watch out for when handling SQL queries in PHP, especially when dealing with variables?

One common error when handling SQL queries in PHP, especially with variables, is SQL injection. To prevent SQL injection, always use prepared statements with parameterized queries to sanitize user input before executing the query.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a placeholder for the variable
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the variable to the placeholder
$stmt->bindParam(':username', $username);

// Execute the query
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();