What are the best practices for structuring PHP code to handle form submissions, database interactions, and page reloading within the same file?

When handling form submissions, database interactions, and page reloading within the same file in PHP, it is best practice to separate concerns by using functions or classes for different tasks. This helps improve code readability, maintainability, and reusability. Additionally, using conditional statements to check for form submissions and database interactions can help streamline the code flow.

<?php

// Check if the form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    
    // Handle form submission
    // Validate form data
    // Sanitize input data
    
    // Perform database interactions
    // Insert/update/delete data
    
    // Redirect to prevent form resubmission
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
}

// Display the form
?>

<!DOCTYPE html>
<html>
<head>
    <title>Form Submission</title>
</head>
<body>
    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <!-- Form fields go here -->
        <input type="submit" value="Submit">
    </form>
</body>
</html>