How can PHP variables be properly used in MySQL queries to prevent errors like 'Unknown column'?

When using PHP variables in MySQL queries, it is important to properly sanitize and escape the variables to prevent SQL injection attacks and errors like 'Unknown column'. One way to do this is by using prepared statements with placeholders for the variables in the query. This ensures that the variables are treated as values rather than column names, reducing the risk of errors.

// Example code snippet using prepared statements to prevent errors with PHP variables in MySQL queries

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Define the SQL query with a placeholder for the variable
$query = "SELECT * FROM mytable WHERE column_name = :variable";

// Prepare the query
$stmt = $pdo->prepare($query);

// Bind the variable to the placeholder
$stmt->bindParam(':variable', $variable_value);

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

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

// Loop through the results
foreach ($results as $row) {
    // Access the data using column names
    echo $row['column_name'];
}