What potential pitfalls can arise when passing variables in a URL for SQL queries in PHP?
When passing variables in a URL for SQL queries in PHP, a potential pitfall is SQL injection attacks where malicious SQL code is injected into the query. To prevent this, you should always sanitize and validate the input data before using it in a query. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input.
// Retrieve the variable from the URL and sanitize it
$id = filter_input(INPUT_GET, 'id', FILTER_SANITIZE_NUMBER_INT);
// Create a prepared statement to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM table WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);