Are there any best practices for handling user input from HTML forms and using it in PHP scripts for database queries?

When handling user input from HTML forms in PHP scripts for database queries, it is crucial to sanitize and validate the input to prevent SQL injection attacks and ensure data integrity. One common best practice is to use prepared statements with parameterized queries to securely interact with the database.

// Example of handling user input from an HTML form in PHP
// Assuming a form field named 'username' is submitted

// Sanitize and validate the user input
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);

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

// Fetch the results or handle errors accordingly
$results = $stmt->fetchAll();