What are some common pitfalls to avoid when passing variables to SQL queries in PHP?

One common pitfall to avoid when passing variables to SQL queries in PHP is SQL injection. To prevent SQL injection, you should always use prepared statements with parameterized queries instead of directly interpolating variables into your SQL queries.

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

// Prepare a SQL query 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();