What are some best practices for validating user input in PHP to avoid issues like the one described in the code snippet?

The issue described in the code snippet is that the user input is directly concatenated into a SQL query, making it vulnerable to SQL injection attacks. To avoid this issue, it is best practice to validate and sanitize user input before using it in a query. One way to do this is to use prepared statements with parameterized queries to securely interact with the database.

// Validate and sanitize user input
$user_input = $_POST['user_input'];
$validated_input = filter_var($user_input, FILTER_SANITIZE_STRING);

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

// Fetch results
$results = $stmt->fetchAll();
foreach ($results as $row) {
    // Process results
}