What are the best practices for directly accessing values from $_GET in PHP for database operations?

When directly accessing values from $_GET in PHP for database operations, it is important to sanitize and validate the input to prevent SQL injection attacks. One common practice is to use prepared statements with parameterized queries to securely interact with the database. Additionally, it is recommended to use filter_input() function to sanitize the input data before using it in database queries.

// Sanitize and validate input from $_GET
$user_id = filter_input(INPUT_GET, 'user_id', FILTER_SANITIZE_NUMBER_INT);

// Prepare a SQL statement using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :user_id");
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();

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