What are some best practices for handling form submissions and database interactions in PHP scripts?

Issue: When handling form submissions and database interactions in PHP scripts, it is important to sanitize user input to prevent SQL injection attacks and validate data to ensure it meets the expected format before interacting with the database.

// Sanitize user input to prevent SQL injection
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);

// Validate data to ensure it meets the expected format
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    die("Invalid email format");
}

// Perform database interactions using prepared statements
$stmt = $conn->prepare("INSERT INTO users (username, password, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $username, $password, $_POST['email']);
$stmt->execute();
$stmt->close();