How To Insert 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.

Inserting HTML Form Data Into MySQL Database Using PHP

Steps #
  1. Setup your PHP Development Environment.
  2. Create a MySQL database.
  3. Create a MySQL Table.
  4. Create Your Project Folder.
  5. Build HTML Form.
  6. PHP Code To Insert Form Data Into MySQL Database.
  7. Testing

1. Setup your PHP Development Environment:

If you have a PHP Development Environment, you can skip this step. But If you don’t have then 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 web-server and MySQL server are running.
  2. Go to your phpMyAdmin and create a database called my_test_db.
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 columnsname, 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 mysql users table in the my_test_db database

4. Create Your Project Folder:

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.
    • index.html will contain the HTML form.
    • insert.php will contain the code to insert data into the database.
htdocs php folder structure

5. Create HTML Form (index.html)

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

<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>

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

Now 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. PHP Code To Insert 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.

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.

Demo of inserting form data into MySQL database using PHP

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.. 🙏🏻❤️❤️