What are the best practices for structuring PHP code, particularly when dealing with database connections and queries within HTML forms?

When structuring PHP code for handling database connections and queries within HTML forms, it is best practice to separate your PHP logic from your HTML presentation by using a Model-View-Controller (MVC) architecture. This helps to improve code organization, readability, and maintainability. In this approach, the PHP code for database connections and queries should be placed in the Model, while the HTML form should be in the View.

// Model - database connection and query logic
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Query example
$sql = "SELECT * FROM users";
$result = $conn->query($sql);

// View - HTML form
<!DOCTYPE html>
<html>
<head>
    <title>HTML Form</title>
</head>
<body>
    <form action="process_form.php" method="POST">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name"><br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>