Logo

How to Submit a Form in PHP?

How to Submit a Form in PHP?

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.

				
					<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PHP Form Submission Example</title>
</head>
<body>
    <h2>Contact Form</h2>
    <form id="contactForm" action="submit_form.php" method="post" enctype="multipart/form-data">
        <label for="name">Name:</label><br>
        <input type="text" id="name" name="name" required><br><br>

        <label for="email">Email:</label><br>
        <input type="email" id="email" name="email" required><br><br>

        <label for="phone">Phone:</label><br>
        <input type="tel" id="phone" name="phone" required><br><br>

        <label for="gender">Gender:</label><br>
        <input type="radio" id="male" name="gender" value="male" required>
        <label for="male">Male</label><br>
        <input type="radio" id="female" name="gender" value="female" required>
        <label for="female">Female</label><br><br>

        <label for="hobbies">Hobbies:</label><br>
        <input type="checkbox" id="hobby1" name="hobbies[]" value="reading">
        <label for="hobby1">Reading</label><br>
        <input type="checkbox" id="hobby2" name="hobbies[]" value="travelling">
        <label for="hobby2">Travelling</label><br><br>

        <label for="country">Country:</label><br>
        <select id="country" name="country" required>
            <option value="usa">USA</option>
            <option value="canada">Canada</option>
            <option value="uk">UK</option>
        </select><br><br>

        <label for="profile_picture">Profile Picture:</label><br>
        <input type="file" id="profile_picture" name="profile_picture" required><br><br>

        <input type="submit" value="Submit">
    </form>

    <div id="response"></div>

    <script>
        const form = document.getElementById('contactForm');
        const responseDiv = document.getElementById('response');

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            const formData = new FormData(form);

            const response = await fetch('submit_form.php', {
                method: 'POST',
                body: formData,
            });

            const result = await response.json();

            if (result.success) {
                responseDiv.innerHTML = `<p style="color: green;">${result.message}</p>`;
            } else {
                responseDiv.innerHTML = `<p style="color: red;">${result.message}</p>`;
            }
        });
    </script>
</body>
</html>

				
			

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.

				
					<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_submission_db";

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

// Check connection
if ($conn->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:

  1. 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.
  2. Move Files to the Server Directory: Place index.html and submit_form.php in the htdocs directory (for XAMPP) or the htdocs directory inside MAMP.

Access the Form in Your Browser:

  1. Start Your Web Server: Open XAMPP or MAMP and start Apache and MySQL.
  2. Navigate to the Form: Open your browser and go to http://localhost/index.html.
  3. 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!

Scroll to Top