Are there any best practices for organizing and structuring PHP code when working with form submissions and database interactions?
When working with form submissions and database interactions in PHP, it is important to separate concerns and follow best practices for organization and structure. One common approach is to create separate files or classes for handling form submissions, database interactions, and business logic. This helps to keep the code modular, maintainable, and easier to debug.
// Form submission handling
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate form data
$name = $_POST['name'];
$email = $_POST['email'];
// Database interaction
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $db->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
// Redirect after form submission
header("Location: thank-you.php");
exit();
}