What are some best practices for creating and displaying form data on a webpage using PHP?

When creating and displaying form data on a webpage using PHP, it is important to properly sanitize and validate the input data to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, it is recommended to use prepared statements when interacting with a database to further protect against SQL injection. Finally, ensure that the displayed data is properly escaped to prevent any HTML or JavaScript injection.

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

// Connect to database and insert form data using prepared statements
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();

// Display the submitted data on the webpage
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email);
?>