Add Remove Dynamic HTML Fields using Jquery repeater in PHP with Mysql


In this tutorial you will learn how to create dynamic HTML fields using the Jquery plugin and how to insert dynamically generated HTML field data into MySQL tables using PHP with Ajax. Here we are using the Jquery repeater plugin to generate dynamic input fields by adding more and removing buttons in HTML form. While we are working on my project, we want to generate dynamic HTML with 10 input fields in my form. So at this point we have a data set with Jquery code to generate dynamic HTML fields. Now that we have recorded the number of lines of Jquery code, we need to create 10 dynamic HTML fields. But then our website slows down. We currently have a search on a jquery plugin that allows us to generate dynamic HTML fields. So we found that this Jquery repeater is active. With the help of this plugin we can easily add or remove dynamic HTML fields in our forms.

Here we share this tutorial for web developers working on forms with multiple input fields. Insertion of multiple input fields, which should dynamically generate input fields by writing a few lines of jquery code, depends on our needs for the input fields. However, with the help of this JQuery Repeater plugin, this type of dynamic HTML field creation has become much easier. This JQuery plugin is also very useful for adding multiple form elements to PHP as it generates the same name we defined under the data name attribute. Therefore, in this post we explain how we can use this plugin to dynamically generate input fields in a form and pass these dynamically generated values ​​to input fields in a database using Ajax with PHP.

If we want to create a function like generating a dynamic field for inserting HTML into our form, we can perform this function using this plugin by writing very short code. We can easily add or remove dynamically generated input fields. Then we want to process this set of fields and insert them into a MySQL table. We use Ajax requests for this purpose. With Ajax requests, we send dynamically generated data for HTML fields to be included in the PHP script. So with Ajax we can enter data for dynamic input fields into MySQL tables without updating the web page. After pasting some data for the input fields into the database, the form became clear. In this tutorial we saw how dynamic input fields are created with the Jquery repeater plugin and fed into MySQL using Ajax with PHP.

Create Database and Table by SQL query

In first step, we need to create database and table, so here I created webscodex database and customers table with id, customer_details column . You can simply create countries table as following SQL query.

Customers MySQL Table Structure

-- Database: `webscodex`
-- Table structure for table `customers`
--
CREATE TABLE `customers` (
  `id` int(100) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `customer_details` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `customers`
--
INSERT INTO `customers` (`id`, `customer_details`) VALUES
(1, '[{\"name\":\"manish\",\"qualification\":\"mca\",\"email\":\"manish12@gmail.com\",\"age\":\"25\"},{\"name\":\"manoj\",\"qualification\":\"ba\",\"email\":\"manoj12@gmail.com\",\"age\":\"24\"},{\"name\":\"vijay\",\"qualification\":\"ba\",\"email\":\"vijay12@gmail.com\",\"age\":\"18\"}]'),
(2, '[{\"name\":\"manish\",\"qualification\":\"mca\",\"email\":\"manish12@gmail.com\",\"age\":\"25\"},{\"name\":\"manoj\",\"qualification\":\"ba\",\"email\":\"manoj12@gmail.com\",\"age\":\"24\"},{\"name\":\"vijay\",\"qualification\":\"ba\",\"email\":\"vijay12@gmail.com\",\"age\":\"18\"}]'),
(3, '[{\"name\":\"manish\",\"qualification\":\"bca\",\"email\":\"manish12@gmail.com\",\"age\":\"25\"},{\"name\":\"manoj\",\"qualification\":\"bca\",\"email\":\"manoj12@gmail.com\",\"age\":\"24\"},{\"name\":\"vijay\",\"qualification\":\"ba\",\"email\":\"vijay12@gmail.com\",\"age\":\"18\"}]'),
(4, '[{\"name\":\"manish\",\"qualification\":\"mca\",\"email\":\"manish12@gmail.com\",\"age\":\"25\"},{\"name\":\"manoj\",\"qualification\":\"ba\",\"email\":\"manoj12@gmail.com\",\"age\":\"24\"}]');

Created Database Configuration File

In this step, we require to create database configuration file, here we will set database name, username and password. So let’s create config.php file on your root directory and put bellow code:

config.php

<?php
	// Database configuration 	
	$hostname = "localhost"; 
	$username = "root"; 
	$password = ""; 
	$dbname   = "webscodex";
	 
	// Create database connection 
	$con = new mysqli($hostname, $username, $password, $dbname); 
	 
	// Check connection 
	if ($con->connect_error) { 
	    die("Connection failed: " . $con->connect_error); 
	}
?>

Create Jquery Repeater plugin HTML Form Page

In this step, we require to create add file in HTML for add user name, input, qualification as select option, email as a input field and age as input fields.this select option is show some static courses name insert in table dynamically using Jquery repeater plugin with PHP MySQL. we add all jquery CDN link and also repeater plugin CDN link.

add.php

<?php
  
  //Include database connection file
  include_once('config.php');
  if (!empty($_POST) && isset($_POST)) {
    $postData = $_POST['userData'];
    $postData = json_encode($postData);
      
    $query = "INSERT INTO customers (customer_details) VALUES('$postData')";
    $result = $con->query($query);
    if ($result==true) {
        echo "<script>alert('Data inserted successful')</script>";
        header("Location:index.php");
    }else{
        echo "<script>alert('Data not inserted try again')</script>";    
    }
  }
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Add Remove Dynamic HTML Fields using JQuery repeater in PHP with Mysql</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">
</head>
<body>
<div class="card bg-success text-white text-center" style="padding:20px;">
  <h3>Add Remove Dynamic HTML Fields using JQuery repeater in PHP with Mysql</h3>
</div><br>
<div class="container">
  <form method="POST">    
    <div class="repeater">
      <div data-repeater-list="userData">
        <div data-repeater-item>
            <div class="row">
              <div class="form-group col-md-3">
                <input type="text" name="name" class="form-control" placeholder="Enter name" required="" />
              </div>
              <div class="form-group col-md-2">
                <select class="form-control" name="qualification" required="">
                  <option value="">Select Qualification</option>  
                  <option value="bca">BCA</option>
                  <option value="mca">MCA</option>
                  <option value="bsc">B.sc</option>
                  <option value="msc">M.sc</option>
                  <option value="ba">BA</option>
                </select>
              </div>
              <div class="form-group col-md-3">
                <input type="email" name="email" class="form-control" placeholder="Enter email" required=""/>
              </div>
              <div class="form-group col-md-3">
                <input type="age" name="age" class="form-control" placeholder="Enter age" required=""/>
              </div>
              <div class="form-group col-md-1">
                <button type="button" class="btn btn-danger btn-md" data-repeater-delete="">Delete</button>
              </div>          
          </div>
        </div>
      </div>
      <input data-repeater-create type="button" class="btn btn-success btn-sm" value="Add More"/><br><br>
      <input type="submit" name="submit" class="btn btn-primary" value="Submit">
    </div>
  </form>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.repeater/1.2.1/jquery.repeater.js"></script>
<script type="text/javascript">
  $(document).ready(function () {
    $('.repeater').repeater({
      show: function () {
        $(this).slideDown();
      },
      hide: function (deleteElement) {
         if(confirm('Are you sure you want to delete this element?')) {
            $(this).slideUp(deleteElement);
         }
      },        
    });
  });
</script>
</body>
</html>

Create PHP File for display repeater data

In this step display the record.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Add Remove Dynamic HTML Fields using JQuery repeater in PHP with Mysql</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">
</head>
<body>
<div class="card bg-success text-white text-center" style="padding:20px;">
  <h3>Add Remove Dynamic HTML Fields using JQuery repeater in PHP with Mysql</h3>
</div><br>
<div class="row">
  <div class="col-md-10"></div>
  <div class="col-md-2">
    <a href="add.php" class="btn btn-primary">Add more</a>
  </div>  
</div><br>
<div class="container">
  <div class="row">
    <table class="table table-striped">
      <thead>
        <tr>          
          <th>Name</th>
          <th>Email</th>
          <th>Qualifiction</th>
          <th>Age</th>          
        </tr>
      </thead>
      <tbody>
      <?php
        //Include database connection file
        
        include_once('config.php');
        $query = "SELECT * FROM customers";
        $result = $con->query($query);
        
        if ($result->num_rows > 0) {
        while ($rows = $result->fetch_assoc()) {
        $customers = json_decode($rows['customer_details'], true);
        foreach($customers as $customer){
         
      ?>   
        <tr>         
          <td><?php echo $customer['name'] ?></td>
          <td><?php echo $customer['email'] ?></td>
          <td><?php echo $customer['qualification'] ?></td>
          <td><?php echo $customer['age'] ?></td>          
        </tr>
      <?php      
          }   
        }
      } else {
        echo "<h2>No record found</h2>";
      }
      ?>
      </tbody>
    </table>
  </div>
</div>
</body>
</html>

Display Repeater Data

Conclusion

In this post, we have seen how to Remove Dynamic HTML Fields using JQuery repeater in PHP with Mysql. This function mainly works if you are add remove dynamic HTML fields and save in JSON format in only on column and display record.
You can always support by sharing on social media or recommending my blog to your friends and colleagues. If you have any suggestions / problems about this tutorial, please comment on the  form below.😊


Leave a Reply