What are the best practices for handling data input from a form and inserting it into a database using PHP?

When handling data input from a form and inserting it into a database using PHP, it is important to sanitize the input to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries. Additionally, validating the input data before inserting it into the database can help ensure data integrity.

// Assuming a form with input fields 'name' and 'email'

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

// Sanitize and validate input data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);

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