What are the potential pitfalls of using direct GET variables in SQL queries in PHP?

Using direct GET variables in SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to perform unauthorized actions on the database. To prevent this, it is recommended to use prepared statements with bound parameters when executing SQL queries in PHP. This approach helps sanitize user input and prevent SQL injection vulnerabilities.

// Using prepared statements to prevent SQL injection

// Assuming $conn is the database connection

// Get the value from the GET variable
$id = $_GET['id'];

// Prepare the SQL statement with a placeholder for the parameter
$stmt = $conn->prepare("SELECT * FROM table WHERE id = ?");

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

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

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

// Process the results as needed
while ($row = $result->fetch_assoc()) {
    // Process each row
}

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