Fri. May 2nd, 2025

sarveshpathak.com

Code Snippets, Tutorials, Articles, Technical Stuff

How to Dynamically Add / Remove row with multiple input fields in PHP Form

2 min read
Dynamically Add / Remove row with multiple input

Dynamically Add / Remove row with multiple input

How to Dynamically Add / Remove row with multiple input fields in PHP Form

Here we will understand the following points on how to Dynamically Add / Remove rows with multiple input fields in PHP Form using Java Script

1- How to Create Add New Row Feature in the Form

2-How to Create Dynamic form with a Dynamic Dropdown

3- How to Insert Data in MySQL Table from Dynamic Form

4- How to Create Dynamic Character Counter in the Text area

4- How to Show data in Tables

MySQL Table structure Dynamically Add / Remove row with multiple input fields

Demo

1--
2-- Table structure for table `mis_production`
3--
4 
5CREATE TABLE `mis_production` (
6  `sr_id` int(11) NOT NULL,
7  `fin_year` varchar(20) NOT NULL,
8  `production` int(11) NOT NULL,
9  `remarks` varchar(60) NOT NULL
10) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
11--
12-- Table structure for table `mis_year`
13--
14 
15CREATE TABLE `mis_year` (
16  `sr_id` int(11) NOT NULL,
17  `fin_year` varchar(20) NOT NULL
18) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
19Dynamically Add / Remove row with multiple input fields in PHP Form using  Javascript

Connect Database

1define('DB_SERVER','localhost');
2define('DB_USER','root');
3define('DB_PASS' ,'');
4define('DB_NAME', 'school');
5$con = mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

Create PHP Method to Bind Dropdown

1function fill_year_select_box($con)
2{
3$output = '';
4$query=mysqli_query($con,"SELECT fin_year FROM mis_year");
5$cnt=1;
6while($row=mysqli_fetch_array($query))
7{
8$output .= " $row[0] ";
9}
10return $output;
11}
12Dynamically Add / Remove row with multiple input fields in PHP Form using  Javascript

Create JavaScript Method To calculate Text Length

1    <script>
2    //Method to show remaning text
3      function countChar(val,$msg,$ct) {
4          $text1=count_message;
5        var len = val.value.length;
6        if (len >= $ct) {
7          val.value = val.value.substring(0, $ct);
8        } else {
9          $($msg).text($ct - len);
10        }
11      };
12   
13</script>

JavaScript Method to Create a New Row

1<script type="text/javascript">
2// Method to create new Row
3function add_row()
4{
5 $rowno=$("#employee_table tr").length;
6 $rowno=$rowno+1;
7  
8 
9 $second="<td>"+$rowno-1+"</td><td><select  name='financial_year[]' class='form-control'  required><option value=''>Financial Year</option> <?php echo fill_year_select_box($con);?></select></td>";
10 $fourth="<td><input type='number' class='form-control' name='production[]' placeholder=' Add Total Production'/></td>";
11 $fifth="<td><textarea rows = '2' cols = '20' onkeyup='countChar(this,count_message"+$rowno+",50)' id='remarks' name='remarks[]' class='char-counter maxlength='50' form-control form-control-sm' rows='2' placeholder='Remarks'  > </textarea><br/><span class='pull-right label label-default' id='count_message"+$rowno+"'>50</span> Character(s) Remaining </td>";
12 $("#employee_table tr:last").after("<tr id='row"+$rowno+"' class='border-bottom-primary'>"+$second+""+$fourth+""+$fifth+" <td><a href='#' class='btn btn-danger btn-circle btn-sm' onclick=delete_row('row"+$rowno+"')><i class='fas fa-trash'></i>Remove</a> </td></tr>");
13}
14function delete_row(rowno)
15{
16 $('#'+rowno).remove();
17}
18</script>
19Dynamically Add / Remove row with multiple input fields in PHP Form using  Javascript

Create Form in PHP

1<form class="form-horizontal" name="insertstore" method="post"  enctype="multipart/form-data">
2                                        <?php echo $msg; ?>
3                                     
4                                                <div class="form-group row">
5                                                <table id="employee_table" class="table table-bordered dataTable" align=center>
6                                                <tr ><th class="border-bottom-primary"> Select Financial Year</th><th class="border-bottom-primary">Production in numbers</th><th class="border-bottom-primary"> Remarks </th>  <th rowspan="1" > Remove</th> </tr>
7                                                <tr id="row1" class="border-bottom-primary">
8                                                <td>
9                                                    <select id="financial_year" name="financial_year[]"  class="form-control"  required>
10                                                <option value="">Financial Year</option>
11                                                <?php echo fill_year_select_box($con);?> 
12                                                </select>
13                                                </td>
14                                                <td><input type="number" name="production[]"class="form-control" placeholder="Add Total Production"> </td>
15                                                 
16                                                <td>
17                                                <textarea rows = "2" cols = "20" onkeyup="countChar(this,count_message,50)" maxlength="50" id="remarks" name="remarks[]" class="char-counter form-control form-control-sm" rows="2" placeholder="Remarks" > </textarea>
18                                                 
19                                                            <span class="pull-right label label-default" id="count_message">50</span> Character(s) Remaining
20                                                 </td>
21                                                        </tr>
22                                                    </table>
23                                                    </div>
24                                                     
25                                            
26                                             
27                                            <div class="form-group row">                                         
28                                                    <label class="col-sm-5 col-form-label" for="inputLastName"></label>
29                                                     <div class="col-sm-6">
30                                                     <input class="btn btn-warning" type="button" onclick="add_row();" value="Add New Row">
31                                                    <button type="submit" name="submit" class="btn btn-primary">Final Save</button></div>                                      
32                                                 
33                                            </div>
34                                            
35                                             
36                                             
37                                        </form>

Save Form Data

1<?php
2if(isset($_POST['submit']))
3{
4    $itemCount = count($_POST["financial_year"]);
5    $query = "INSERT INTO mis_production (fin_year, production,remarks) VALUES ";
6        $queryValue = "";
7        for($i=0;$i<$itemCount;$i++) {
8            if(!empty($_POST["production"][$i]) || !empty($_POST["financial_year"][$i])) {
9                $itemValues++;
10                if($queryValue!="") {
11                    $queryValue .= ",";
12                }
13                $queryValue .= "('" . $_POST["financial_year"][$i] . "', " . $_POST["production"][$i] . ", '" . $_POST["remarks"][$i] . "')";
14            }
15        }
16        $sql = $query.$queryValue;
17         
18        if($itemValues!=0) {
19            $result = mysqli_query($con, $sql);
20             
21            if(!empty($result)) $message = "Added Successfully.";
22            $msg="<div class='alert alert-success '><strong>Welcome!".$row['sr_id']."</strong> Added Successfully<button type='button' class='close' data-dismiss='alert'>×</button> </div>";
23 
24        }
25     
26    }
27?>

Show Saved Records

1<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
2                                    <thead>
3                                        <tr>
4                                            <th>ID</th>
5                                            <th>Financial Year</th>
6                                            <th>Production in numbers</th>
7                                            <th>Remarks</th>
8                                             
9                                        </tr>
10                                    </thead>
11                                     
12                                    <tbody>
13                                    <?php
14         
15                        $command="SELECT * from mis_production ";
16                        $query=mysqli_query($con,$command);
17                        $cnt=1;
18                        while($row=mysqli_fetch_array($query))
19                        {
20                        ?>      
21                                        <tr>
22                                            <td><?php echo htmlentities($row['sr_id']);?></td>
23                                            <td><?php echo htmlentities($row['fin_year']);?></td>
24                                            <td><?php echo htmlentities($row['production']);?></td>                                          
25                                            <td><?php echo htmlentities($row['remarks']);?></td>
26                                             
27                                        </tr>
28                        <?php }?>
29                                    </tbody>
30                                </table>
31Dynamically Add / Remove row with multiple input fields in PHP Form using  Javascript

Download Source Code Click Me

View Demo

Dynamically Add / Remove row with multiple input
Dynamically Add / Remove row with multiple input

About Post Author

13 thoughts on “How to Dynamically Add / Remove row with multiple input fields in PHP Form

  1. you have an excellent blog site below! would certainly you such as to make some invite blog posts on my blog site? Esther Emmy Clancy

  2. Superb site you have here but I was wondering if you knew of any user discussion forums that cover the same topics discussed here?
    I’d really love to be a part of group where I can get advice from other knowledgeable individuals that share the same interest.

    If you have any recommendations, please let me know.
    Many thanks!

  3. Generally I do not read article on blogs, but I would like to say that this write-up very forced me to take a look at and do it! Your writing taste has been surprised me. Thanks, quite nice post. Clarinda Emile Yablon

  4. Pingback: Google
  5. Pingback: buy sig p365
  6. Pingback: Moroccan hash

Comments are closed.