What are common pitfalls when using variables in MySQL queries in PHP?

Common pitfalls when using variables in MySQL queries in PHP include not properly escaping the variables, leaving the code vulnerable to SQL injection attacks, and not using prepared statements which can improve performance and security. To solve these issues, always use prepared statements with placeholders for variables and bind the variables to the statement before execution.

// Example of using prepared statements with variables in MySQL queries in PHP
$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 statement
$username = "john_doe";
$stmt->bindParam(':username', $username);

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

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}