What is the best practice for handling form submissions in PHP?
When handling form submissions in PHP, it is important to validate the data to ensure it is safe and accurate before processing it. One common practice is to use server-side validation to check for required fields, data types, and any specific formatting rules. Additionally, it is recommended to use prepared statements or parameterized queries to prevent SQL injection attacks when interacting with a database.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate form data
$name = $_POST['name'];
$email = $_POST['email'];
if (empty($name) || empty($email)) {
echo "Name and email are required";
} else {
// Process form data
// Insert data into database using prepared statements
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
echo "Form submitted successfully";
}
}
?>