How can SQL injection be prevented when using GET data in a query?

SQL injection can be prevented when using GET data in a query by using prepared statements with parameterized queries. This approach ensures that user input is treated as data rather than executable code, effectively preventing malicious SQL injection attacks.

// Establish a database connection
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

// Bind the GET parameter to the query
$stmt->bindParam(':username', $_GET['username']);

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

// Fetch results
$results = $stmt->fetchAll();