What are the best practices for handling form data in PHP when querying a database?

When handling form data in PHP and querying a database, it is important to sanitize and validate the input data to prevent SQL injection attacks. One way to achieve this is by using prepared statements with parameterized queries. This helps to separate the SQL query from the user input, making it safer to interact with the database.

// Assuming $db is your database connection

// Sanitize and validate form data
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

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

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

// Use the $user data as needed