How to Submit a Form in PHP?
When developing a website, one of the most common tasks you’ll encounter is handling form submissions.
Forms are crucial for collecting user input and can include a variety of fields such as text inputs, radio buttons, checkboxes, file uploads, dropdowns, emails, and phone numbers.
In this tutorial, we’ll cover how to submit a form using PHP and store the data in a MySQL database, providing a comprehensive example that includes all these form fields.
Step 1 : Set Up Database and Table
Before handling form submissions, you need a database to store the collected data. We’ll use MySQL for this example.
CREATE DATABASE form_submission_db;
USE form_submission_db;
CREATE TABLE contacts (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(15) NOT NULL,
gender VARCHAR(10) NOT NULL,
hobbies TEXT,
country VARCHAR(50) NOT NULL,
profile_picture VARCHAR(255) NOT NULL
);
Step 2 : Create the HTML Form
First, let’s create an HTML form that includes different types of input fields. Save this as index.html
.
PHP Form Submission Example
Contact Form
Step 3 : PHP Script to Handle Form Submission
Next, create the submit_form.php
file to handle the form submission and store data in a MySQL database.
connect_error) {
die(json_encode(['success' => false, 'message' => 'Connection failed: ' . $conn->connect_error]));
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Sanitize and validate input fields
$name = htmlspecialchars(strip_tags(trim($_POST["name"])));
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$phone = htmlspecialchars(strip_tags(trim($_POST["phone"])));
$gender = htmlspecialchars(strip_tags(trim($_POST["gender"])));
$hobbies = isset($_POST["hobbies"]) ? implode(", ", $_POST["hobbies"]) : "";
$country = htmlspecialchars(strip_tags(trim($_POST["country"])));
// Handle file upload
if (isset($_FILES["profile_picture"]) && $_FILES["profile_picture"]["error"] == 0) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["profile_picture"]["name"]);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Check if file is an image
$check = getimagesize($_FILES["profile_picture"]["tmp_name"]);
if ($check !== false) {
if (move_uploaded_file($_FILES["profile_picture"]["tmp_name"], $target_file)) {
$profile_picture = $target_file;
} else {
echo json_encode(['success' => false, 'message' => 'Sorry, there was an error uploading your file.']);
exit;
}
} else {
echo json_encode(['success' => false, 'message' => 'File is not an image.']);
exit;
}
}
// Insert data into the database
$sql = "INSERT INTO contacts (name, email, phone, gender, hobbies, country, profile_picture)
VALUES ('$name', '$email', '$phone', '$gender', '$hobbies', '$country', '$profile_picture')";
if ($conn->query($sql) === TRUE) {
echo json_encode(['success' => true, 'message' => 'Form data submitted successfully.']);
} else {
echo json_encode(['success' => false, 'message' => 'Error: ' . $conn->error]);
}
$conn->close();
} else {
echo json_encode(['success' => false, 'message' => 'Invalid request method.']);
}
?>
Step 4 : Testing the Form Submission
To test the form, place both index.html
and submit_form.php
files on your web server. Make sure you have a MySQL database set up with a table named contacts
. The table structure is provided above.
Set Up Your Web Server:
- Install XAMPP or MAMP: If you don’t have a web server set up, you can install XAMPP (Windows) or MAMP (Mac) which include Apache, MySQL, and PHP.
- Move Files to the Server Directory: Place
index.html
andsubmit_form.php
in thehtdocs
directory (for XAMPP) or thehtdocs
directory inside MAMP.
Access the Form in Your Browser:
- Start Your Web Server: Open XAMPP or MAMP and start Apache and MySQL.
- Navigate to the Form: Open your browser and go to
http://localhost/index.html
. - Fill Out and Submit the Form: Fill out the form and submit it. The data will be stored in the database, and a success or failure message will be displayed on the UI.
Conclusion :
Handling form submissions in PHP involves creating an HTML form, a PHP script to process the submitted data, and optionally storing the data in a database. This example demonstrates a basic form with various input types and file upload handling. For a real-world application, consider adding more robust validation, error handling, and security measures.
Stay tuned for more detailed guides on different methods of form submission in PHP!