Inserting Data into a MySQL Database Table

To INSERT INTO statement is used to insert new rows in a database table.

The Insert Data into a Database from an HTML Form.

The previous section we have learned how to insert data into database from a PHP script. Now we will see how we can insert data into database obtained from an HTML form. Let's create an HTML form that can be used to insert new records to user table.

Step 1: Creating the HTML Form

Now you create user.php file.

<!DOCTYPE html>
<html lang="en">
  <title>Insert data</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="">
  <script src=""></script>
  <script src=""></script>
  <script src=""></script>

<div class="container">
<form action="user_procccess.php" method="post">
    <label for="firstName">First Name:</label>
    <input type="text" name="first_name" id="firstName" class="form-control">
    <label for="lastName">Last Name:</label>
    <input type="text" name="last_name" id="lastName" class="form-control">
    <label for="email">Email:</label>
    <input type="text" name="email" id="email" class="form-control">
    <input type="submit" value="Submit" class="btn btn-primary">


Step 2: Retrieving and Inserting the Form Data

When a user clicks the submit button of the add record HTML form, in the example above, the form data is sent to user_procccess.php file. The user_procccess.php file connects to the MySQL database server, retrieves forms fields using the PHP $_POST variables and finally execute the insert query to add the records. Here is the complete code of our user_procccess.php file.

    $link = mysqli_connect("localhost", "root", "", "demo");

    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());

    $first_name = $_REQUEST['first_name'];
    $last_name = $_REQUEST['last_name'];
    $email = $_REQUEST['email'];

    // Attempt insert query execution
    $sql = "INSERT INTO user (first_name, last_name, email) VALUES ('$first_name', '$last_name', '$email')";
    if(mysqli_query($link, $sql)){
        echo "Records added successfully.";
    } else{
        echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);

Let us execute this example by visiting the following URL in the browser. This URL may be different based on your site.