How can the use of $_GET variables in SQL queries be optimized to prevent SQL syntax errors?

When using $_GET variables in SQL queries, it is important to sanitize and validate the input to prevent SQL injection attacks and syntax errors. One way to optimize this is to use prepared statements with parameterized queries, which separate the SQL code from the user input. This helps to ensure that the input is treated as data rather than executable code.

// Assuming a database connection has been established

// Sanitize and validate the $_GET variable
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM table_name WHERE id = :id");

// Bind the sanitized variable to the query
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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

// Use the results as needed
foreach ($results as $row) {
    // Do something with the data
}