What security risks are associated with directly using $_GET variables in SQL queries, and what are some best practices to prevent them?

Using $_GET variables directly in SQL queries can lead to SQL injection attacks, where malicious users can manipulate the query to access, modify, or delete data in the database. To prevent this, it is recommended to sanitize and validate the input before using it in the query. One way to do this is by using prepared statements with parameterized queries, which separate the SQL code from the user input.

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

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

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

// Bind the sanitized input to the placeholder
$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) {
    echo $row['username'] . "<br>";
}