What are the best practices for handling PHP variables in SQL queries to avoid errors like "Unknown column"?

When using PHP variables in SQL queries, it is important to properly sanitize and escape the variables to prevent SQL injection attacks and errors like "Unknown column". One way to handle this is by using prepared statements with parameterized queries, which separate the SQL query from the user input. This helps to ensure that the variables are treated as data rather than executable code.

// Example of using prepared statements to handle PHP variables in SQL queries
$mysqli = new mysqli("localhost", "username", "password", "database");

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

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

// Assign the PHP variable to the parameter 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();