How can prepared statements improve the security and efficiency of PHP queries, especially when dealing with user input like $_GET variables?

Prepared statements can improve the security and efficiency of PHP queries by separating SQL code from user input, preventing SQL injection attacks. This is especially important when dealing with user input like $_GET variables, as malicious users can manipulate the input to execute harmful SQL queries. Prepared statements also allow the database to optimize query execution, resulting in better performance.

// Using prepared statements to safely handle user input in PHP queries

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_GET['username']);

// 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>";
}