1K Views
Steps on How to Create Form Using PHP
Creating a form in PHP involves two parts:
- HTML Form: The user inputs data into the form.
- PHP Script: The submitted data is processed using PHP.
Step 1: Create an HTML Form
This form contains input fields and a submit button.
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
action="process.php"→ Sends form data toprocess.phpfor processing.method="post"→ Uses the POST method to send data securely.
Step 2: Process Form Data with PHP
Create process.php to handle the submitted data.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
$_SERVER["REQUEST_METHOD"] == "POST"→ Ensures the form is submitted using POST.$_POST['name']→ Retrieves the form data.htmlspecialchars()→ Prevents XSS attacks by escaping special characters.
Step 3: Add Form Validation (Optional)
To validate inputs before processing:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['name']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Valid Submission!<br>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
} else {
echo "Invalid input. Please check your details.";
}
}
?>
!empty($_POST['name'])→ Ensures the name field is not empty.filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)→ Validates email format.
Step 4: Store Data in a Database (Optional)
If you want to store the submitted data in a MySQL database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
mysqliis used to connect to the MySQL database.real_escape_string()prevents SQL injection.
Final Thoughts
- Use client-side validation (JavaScript) for better UX.
- Use server-side validation (PHP) to ensure security.
- Always sanitize inputs to prevent XSS and SQL injection.
Would you like to add a file upload field or other custom features? 🚀