What are the best practices for handling user input, such as $_GET variables, to prevent SQL injection attacks in PHP scripts?

To prevent SQL injection attacks in PHP scripts when handling user input, it is essential to sanitize and validate any input received from the user. One way to achieve this is by using prepared statements with parameterized queries instead of directly inserting user input into SQL queries. This helps to separate the SQL code from the user input, making it more secure.

// Example of using prepared statements to prevent SQL injection

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

// User input from $_GET variable
$user_input = $_GET['input'];

// Prepare a SQL query with a placeholder
$stmt = $pdo->prepare("SELECT * FROM table WHERE column = :input");

// Bind the user input to the placeholder
$stmt->bindParam(':input', $user_input);

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

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

// Use the results as needed
foreach ($results as $row) {
    // Process the data
}