What are some common pitfalls when using variables in PHP queries, and how can they be avoided?

One common pitfall when using variables in PHP queries is not properly sanitizing user input, which can leave your application vulnerable to SQL injection attacks. To avoid this, always use prepared statements with parameterized queries to securely pass variables into your SQL queries.

// Example of using prepared statements with parameterized queries to avoid SQL injection

// Assume $conn is a valid database connection

// User input
$user_input = "John";

// Prepare a statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $user_input);

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

// Get the result
$result = $stmt->get_result();

// Fetch the data
while ($row = $result->fetch_assoc()) {
    // Process the data
}

// Close the statement
$stmt->close();