How To Insert Form Data Into Database Using PHP

Insert HTML Form Data Into Database Using PHP

In web development, it’s common to have forms that collect user data and store it in a database. PHP provides a powerful way to handle form submissions and interact with databases. In this step-by-step tutorial, you will learn how to collect data thorough an HTML form and then insert the data into a MySQL database using PHP.

Before starting I hope you already have PHP development environment with MySQL database because it is required. But if you don’t have then checkout this – setup your PHP development environment by installing XAMPP.

Create a MySQL Database & a Table:

First create a MySQL database and a table inside the database, because here we will store the data collected via an HTML form. Here is the database information:

  • The database name is my_test_db, you can give any name.
  • Now create a table called users inside the my_test_db database. We gave the table name users, because we will store user-related data like – name, age, email.

Hey, if you don’t know how to create a MySQL database checkout this – Learn to Create Database.

After creating the database, create the users table with with four columns – nameageemail, and id.

Also if you don’t know how to create a table in a database, then copy the following SQL code and run or execute the SQL code in the my_test_db database. Checkout this – Learn How to execute SQL code in a database using phpMyAdmin.

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;

Let’s Insert Form Data into the Database:

So now create a project folder where we will create insert.php that contains PHP code for collecting the HTML form data and then inserting the data in the my_test_db database.

And there is one more file we will create called index.html that contains the HTML form where users put their information. And here is most exiting thing to learn that how we can pass the index.html form data to the insert.php and then “insert.php” will insert the data into the database.

To create a project folder, go to your xampp htdocs directory and inside the htdocs folder create a new folder with the name you want, I named it php and this is our project folder. Now we need to create index.html and insert.php inside the php folder or project folder.

htdocs
└── php
    ├── index.html
    └── insert.php

Create an HTML From in the index.html:

Now create index.html in the php folder which is our project directory, and put the following HTML form in the index.html.

<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>
HTML from that collects the users name age and email

There are basically four methods in HTTP to send request data into the server GET, POST, PUT, and DELETE. Among of theme GET and POST are main methods and rest of are similar to the POST method. The differ

GET vs POST: GET sends data via the URL, visible and limited, while POST sends data in the body of the HTTP request, secure and suitable for large amounts of data.

In the above index.html form we have added method="POST" in the <form> which determines that the data of the form will be sent via HTTP POST method to the server.

We have defined the POST method to send the form data to the server but where and therefore we defined action="./insert.php" It tells send the form data here (the location – insert.php). Now the insert.php can access the form data.

Create insert.php and Put the Data Insertion Script in it:

In the previous step we told the HTML to send the form data to Insert.php using the action attribute. Now let’s see how we can collect the requested data and insert it to the database.

In PHP, there is a superglobal variable called $_POST that is used to collect form data sent with the HTTP POST method. And in the following PHP code, this variable is used to access the form data. like – $_POST['u_name'], $_POST['u_age'] and $_POST['u_email']. The u_name, u_age and u_email are the name of the HTML input filed (name="...") you can see in the index.html.

Here is the insert.php code. Read the comments and try to understand. If you don’t understand then ask me in the comment box.

<?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>';

Test it (Try to insert data via form):

Start your apache server and mysql server then open http://localhsot/php/index.html on your browser. Now you can see the html form, go ahead and test it.

Testing of inserting 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.

Any problem! ask in the comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy