What are potential security risks associated with directly using $_GET variables in SQL queries in PHP?

Using $_GET variables directly in SQL queries can make your application vulnerable to SQL injection attacks. To mitigate this risk, you should always sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements with parameterized queries.

// Example of using prepared statements to prevent SQL injection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Sanitize and validate the input
$id = isset($_GET['id']) ? $_GET['id'] : null;

// Prepare the SQL query with a placeholder for the parameter
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind the sanitized input to the parameter placeholder
$stmt->bindParam(':id', $id, PDO::PARAM_INT);

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

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