What best practices should be followed when structuring HTML forms and PHP code for data submission to a database?

When structuring HTML forms and PHP code for data submission to a database, it is important to sanitize user input to prevent SQL injection attacks. This can be done by using prepared statements or parameterized queries in PHP to securely insert data into the database. Additionally, validating user input on the client-side using JavaScript can help improve the user experience by catching errors before the form is submitted.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

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

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

// Sanitize user input
$name = mysqli_real_escape_string($conn, $_POST['name']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
$message = mysqli_real_escape_string($conn, $_POST['message']);

// Prepare and bind SQL statement
$stmt = $conn->prepare("INSERT INTO messages (name, email, message) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $email, $message);

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

// Close the connection
$stmt->close();
$conn->close();