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">
<head>
  <title>Insert data</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>

<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">
</form>
</div>

</body>
</html>

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.

<?php
    $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.

http://localhost/user.php