What is the correct syntax for querying a MySQL table in PHP to avoid SQL syntax errors?

When querying a MySQL table in PHP, it is important to properly sanitize user input to prevent SQL injection attacks and syntax errors. One common way to do this is by using prepared statements with placeholders for the variables in the query. This ensures that the input is treated as data rather than executable SQL code.

// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database_name");

// Prepare the SQL query with placeholders
$stmt = $mysqli->prepare("SELECT * FROM table_name WHERE column_name = ?");

// Bind the parameter to the placeholder
$stmt->bind_param("s", $variable);

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

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

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

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