Insert HTML form data into MySQL Database using PHP

How to Insert Form Data into Database using PHP?

In this tutorial, you will learn how to Insert HTML Form Data into MySQL Database using PHP.

Insert HTML Form Data into MySQL Database using PHP

Here is the Demo (following GIF) –

Demo of inserting form data into MySQL database using PHP

To insert HTML form data into a MySQL database using PHP, you need to follow several steps:

  1. Setup your PHP Development Environment:

    If you have a PHP Development Environment, you can skip this step. But –

    If you don’t have – Setup your PHP development environment by installing XAMPP. Otherwise –

    You cannot proceed to further steps because, we need a web server (Apache), MySQL or MariaDB, obviously PHP, and phpMyAdmin which will help us graphically interact with the database.

  2. Create a MySQL database:
    1. Make sure your Webserver and MySQL server are running.
    2. Go to your phpMyAdmin and create a database called – my_test_db

    See this – If you don’t know How to Create a Database using phpMyAdmin.

    Create a MySQL database
  3. Create a MySQL Table:

    After creating the database, we need to create a table in the my_test_db database where we will store the data received from the HTML Form.

    We will collect user-related data (name, age, email) through HTML form. Therefore –

    In the my_test_db create a table called users with four columns – name, age, email, and id (to uniquely identify each user).

    To create the users table and its four columns run the following SQL Query on the database (my_test_db), or you can create manually.

    CREATE TABLE `users` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(50) NOT NULL,
      `age` int(11) NOT NULL,
      `email` varchar(50) NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;
    create the users table of the database
  4. Where to create HTML and PHP files?

    After successfully creating MySQL Database and Table –

    1. Go to the XAMPP htdocs folder or your server’s www directory.
    2. Inside the htdocs folder, create a new folder called php.
    3. Now, inside the php folder, we need to create two files index.html and insert.php to insert HTML form data into the MySQL my_test_db database.
    htdocs php folder structure
    • index.html will contain the HTML form.
    • insert.php will contain the code to insert data into the database.
  5. Create an HTML form:

    The following is a simple HTML form that will go inside index.html which has three fields – name, age, and email.

    In the form, we have used the POST method to send data to the server (insert.php), Therefore the file (insert.php) path is defined in the action attribute.

    <h1>HTML Form</h1>
    <form action="./insert.php" method="POST">
        <label>Name: </label>
        <input type="text" name="u_name" placeholder="Name"><br><br>
    
        <label>Age: </label>
        <input type="number" name="u_age" placeholder="Age"><br><br>
    
        <label>Email: </label>
        <input type="email" name="u_email" placeholder="Email"><br><br>
        
        <input type="submit" value="Submit">
    </form>

    Open – http://localhost/php/index.html on your browser to see the result of your HTML form.

    The HTML form with the fields - name, age, and email
  6. Inserting the Form data into MySQL Database:

    In step 4, I already said that the insert.php will contain the code to insert data into the database.

    Here is the insert.php file where the form data will be received, and after receiving the data the following PHP code will insert the data into the MySQL database.

    So, put the following PHP code into your insert.php, and to understand the code read the comments.

    <?php
    # -- this is insert.php --
    
    /**
     * The follwing Condition checks whether a client requested the insert.php through
     * the POST method with the u_name, u_age, and u_email
     * 
     * u_name, u_age, and u_email - You can also see these in the HTML Form (index.html) -
     * These are keys to access the actual data provided by a user.
     */
    if (isset($_POST['u_name']) && isset($_POST['u_age']) && isset($_POST['u_email'])) :
    
        # Database Connection my_test_db is the Database name.
        $db_conn = mysqli_connect("localhost", "root", "", "my_test_db");
    
        # Assigning user data to variables for easy access later.
        $name = $_POST['u_name'];
        $age = $_POST['u_age'];
        $email = $_POST['u_email'];
    
        # SQL query for Inserting the Form Data into the users table.
        $sql = "INSERT INTO `users` (`name`, `age`, `email`) VALUES ('$name', $age, '$email')";
    
        # Executing the Above SQL query.
        $query = mysqli_query($db_conn, $sql);
    
        # Checks that the query executed successfully
        if ($query) {
            echo 'New data inserted successfully. <a href="./index.html">Go Back</a>';
        } else {
            echo "Failed to insert new data.";
        }
        exit;
    endif;
    
    /**
     * This message occurs when a user tries to access Insert.php without -
     * the required method and credentials.
     */
    echo '404 Page Not Found. <a href="./index.html">Go Home</a>';
  7. Test it:

    Open http://localhsot/php/index.html and insert HTML Form data into the MySQL database.


The above PHP insert data code is very simple, this code is for giving an Idea to insert data into MySQL DB using PHP.

To insert data securely you have to write more code for implementing form validation, PHP prepared statements.

Thank You.. 🙏🏻❤️❤️