What are the common mistakes to avoid when using PHP variables in MySQL queries?

One common mistake to avoid when using PHP variables in MySQL queries is not properly sanitizing or escaping the variables, which can lead to SQL injection attacks. To prevent this, always use prepared statements with placeholders for variables in your queries. This ensures that the variables are properly escaped and sanitized before being used in the query.

// Example of using prepared statements to avoid SQL injection
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Prepare a SQL statement with a placeholder for the variable
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = ?");
$stmt->bind_param("s", $username);

// Set the variable value and execute the query
$username = "john_doe";
$stmt->execute();

// Fetch results
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    // Process the results
}

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