PHP – Add Dynamic Rows in Table Tag

Learn how to add dynamic rows in a table tag in HTML and Javascript. And also save the data in MySQL database using PHP.

Introduction

Suppose you are trying to generate an invoice for your customers. You wanted to have a functionality where you will be able to add multiple items in an invoice. A simple table tag will be created from where the user will be able to add multiple items. You have added a button labeled as “Add Item” which when clicked will create a new row to add an item.

Now it might sound easy but technically you have to create rows dynamically. Whenever a user clicks on the “Add Item” button, a new row inside table tag should be created and it must be an array as items can be multiple. Then these arrays should be stored in the database using a loop iteration. Following this tutorial, you will be able to do so.

We will be creating 2 tables, although to explain this tutorial only 1 table would be enough but teaching with 2 will help to understand better when you are working on existing projects. We will have 1 table for storing invoices basic data, for example, customer name, etc, and the second table for storing items in that invoice.

“invoices” table

Our first table name is “invoices” and it will have just 2 fields, unique auto-increment ID and customer name. And the second table will be named “items” and have the product name, quantity, etc and also a foreign key that reference for invoice ID.

To add dynamic rows, we are using a <table> tag that will create a table layout so we will add rows in <tbody> tag. As discussed earlier, all rows will be in an array that needs to be stored in the database, so we will create a <form> tag that will help to do this. We are setting the method to POST as the data might be sensitive and long, and action attribute as current file name, you can change this if you want to send data to a different page.

Customer field

We are creating a simple input field for customer name that will be stored in the “invoices” table, you can place your other fields here. Then we are creating a <table> tag and inside it, we will be displaying the number of items, item name, and item quantity. Make sure to give <tbody> tag a unique ID so we can append new rows in it using Javascript.

Below them, we are creating a button which when clicked will call a Javascript function from where we can add a new row inside that table. And finally, a submit button which when clicked will submit the form and we have to save that data in database.

<form method="POST" action="index.php">
	<input type="text" name="customerName" placeholder="Enter customer name" required>

	<table>
		<tr>
			<th>#</th>
			<th>Item Name</th>
			<th>Item Quantity</th>
		</tr>
		<tbody id="tbody"></tbody>
	</table>

	<button type="button" onclick="addItem();">Add Item</button>
	<input type="submit" name="addInvoice" value="Add Invoice">
</form>

Add/delete row

Now we need to create a function which when clicked will add a new node in the <tbody> tag. We have created a variable for the number of items and we are incrementing it on each click. Whenever this function called we are creating a <tr> tag and adding input fields for name and quantity in <td> tags. Notice the “[]” with the input name attribute, this tells that this field will be an array. Lastly, we are creating a new row using tbody function called insertRow() and appending the <tr> HTML in it.

<script>
	var items = 0;
	function addItem() {
		items++;

		var html = "<tr>";
			html += "<td>" + items + "</td>";
			html += "<td><input type='text' name='itemName[]'></td>";
			html += "<td><input type='number' name='itemQuantity[]'></td>";
            html += "<td><button type='button' onclick='deleteRow(this);'>Delete</button></td>"
		html += "</tr>";

		var row = document.getElementById("tbody").insertRow();
		row.innerHTML = html;
	}

function deleteRow(button) {
    items--
    button.parentElement.parentElement.remove();
    // first parentElement will be td and second will be tr.
}
</script>

Style the table

Now we are going to apply some styles on our table just to make it look a little bit good.

<style type="text/css">
	table {
		width: 100%;
		border-collapse: collapse;
	}
	table tr td,
	table tr th {
		border: 1px solid black;
		padding: 25px;
	}
</style>

Add record in database

Now we just need to store this data in our database. The following code must be put at the top of your file. Our database name is “tutorials” but it will be different in your case, make sure to change the DB name accordingly. Next, check if the form is submitted, the if block will only run after the user submits the form. Get the customer name and insert that in the “invoices” table, it is rather simple.

Remember we added “invoiceId” as a foreign key in “items” table. So, we have to get the newly inserted AUTO-INCREMENT ID. Then we are looping through all the added items. You can either use the “itemName” input field or “itemQuantity” and insert them in “items” table with same invoice ID.

<?php

	$conn = mysqli_connect("localhost:8889", "root", "root", "tutorials");

	if (isset($_POST["addInvoice"]))
	{
		$customerName = $_POST["customerName"];

		$sql = "INSERT INTO invoices (customerName) VALUES ('$customerName')";
		mysqli_query($conn, $sql);
		$invoiceId = mysqli_insert_id($conn);

		for ($a = 0; $a < count($_POST["itemName"]); $a++)
		{
			$sql = "INSERT INTO items (invoiceId, itemName, itemQuantity) VALUES ('$invoiceId', '" . $_POST["itemName"][$a] . "', '" . $_POST["itemQuantity"][$a] . "')";
			mysqli_query($conn, $sql);
		}

		echo "<p>Invoice has been added.</p>";
	}

?>

That’s it, the job is done. At this point, you will be able to select multiple items. And add dynamic rows in table tag and inserting them in the database as well. Complete source file along with SQL exported file which will help you to understand the structure of database.

[wpdm_package id=’239′]

17 Replies to “PHP – Add Dynamic Rows in Table Tag”

  1. Hello Adnan, nice to talk to you!
    I saw your video about adding rows dynamically with PHP, and i am doing a little project, but a i have a trouble, I insert a n (Order Number, Provider , Products) the products are what i added dynamically.

    So i want to retrieve those products inserted in my data base, i have n quantity of products for each provider with his own Order number.

    If you can help me with that, let me now how can we get in contact.

    Thanks

    Pablo Agreda

  2. you are so helpful with so many resources here in the page and youtube. thank you so much.

    i find this ‘PHP – Add Dynamic Rows in Table Tag’ is useful for my coding, but a ‘Delete row’ is necessary with each ‘add row’ feature. And some validation in the detail table is also helpful for many of your followers. May I know, how can I get those coding?

    for your kind consideration. thank you again.

    1. Yes, you can add a delete button like this:

      <td><button type=”button” onclick=”deleteRow(this);”>Delete</button></td>

      And then in your Javascript do this:

      function deleteRow(button) {
      button.parentElement.parentElement.remove();
      // first parentElement will be td and second will be tr.
      }

      1. dear adnan,

        function deleteRow(button) {
        button.parentElement.parentElement.remove();
        // first parentElement will be td and second will be tr.
        }

        can you please full codes, this wiill very helpfu to me

        Mr. Sangpo
        Thimphu,Bhutan

  3. Dear Adnan, Thanks for the response to inquiry. There is no error acctuall, but no action is being tken uopn licking delete buton. I have copied the whole code where i have added deleteRow function. Please kind corrct it. Your action with will be very benifical only to me but to all others.

    //var ite = 0;

    // function addItem() {
    // ite++;

    // var ht = “”;
    // ht += “” + ite + “”;
    // ht += “”;
    // ht += “”;

    // ht += “”;

    // var ro = document.getElementById(“tbody”).insertRow();
    // ro.innerHTML = ht;

    //}

    //function deleteRow(button) {
    //button.parentElement.parentElement.remove();
    // first parentElement will be td and second will be tr.
    //}

    //

    Thank you
    Mr. Sangpo, Thimphu, Bhutan

  4. Dear Adnand,
    Please kindly post the same sample code for adding dynamic Row, with adding addtional feauture for deletting rows. This will benefit many persons who are in learning stage

    Thank you.

    Sangpo

  5. Dear Anan,
    This is my next request,
    Your recent updated post on project sample for dynamic Adding and Deleting rows helping me lots And it should be same to all enthusiast in learning programing. We all can use same logic extracted from this sample in making other project.
    Now I on behalf of all. I like to request you to add following additional features.

    1. how to automatically add itemQuantity in the items table, with quantity we enter in form.( I
    tried: )
    2. To show/display in the form ” with new invoice ID ” that will be inserted in the ” invoices table”

    Thank you ,
    Sangpo, Thimphu, Bhutan

    1. Regarding the 1st. Item quantity is already been saved in the database.
      Regarding 2nd. You have to perform the following functions:

      1. On page load, call an AJAX on PHP server.
      2. Get (maximum number of ID + 1) from database table. Follow code below:
      3. Save it in hidden input field.
      4. Get hidden input field value using Javascript.
      5. Increment + 1, each time new row is created.
      6. Decrement – 1, each time row is deleted.


      <?php
      // server side
      $result = mysqli_query($conn, "SELECT MAX(id) AS max_id FROM table_name");
      $row = mysqli_fetch_object($result);
      $max_id = $row->max_id;
      $max_id++;
      echo $max_id;
      ?>

      <!-- user side -->
      <input type="hidden" id="max_id">

      <script>
      // on response of AJAX
      document.getElementById("max_id").value = response;
      </script>

      1. Dear Adnan,
        Thanks for response. I think my 1st request confused you. I actually requested you as below.

        To add up /plus the existing itemquanty in items with new itemquanty being entered in the form. Suppose item A qty is already 100 in items table. Now I am again entering 200 itemquantity . So this 200 should be added to 100 ,thereby totosl itemQuantity of A should be 300.

        I did ….$sql=update items set itemQuantity = itemQuantity+$item where invoiceId=$invoiceid.

        But this not working.

        There fore please help us here with this . If we know this, we can try make small project on inventory.

        Thank you,
        Mr. Sangpo,Thimphu,Bhutan

  6. Dear Adnan,
    Thanks for response. I think my 1st request confused you. I actually requested you as below.

    To add up /plus the existing itemquanty in items with new itemquanty being entered in the form. Suppose item A qty is already 100 in items table. Now I am again entering 200 itemquantity . So this 200 should be added to 100 ,thereby totosl itemQuantity of A should be 300.

    I did ….$sql=update items set itemQuantity = itemQuantity+$item where invoiceId=$invoiceid.

    But this not working.

    There fore please help us here with this . If we know this, we can try make small project on inventory.

    Thank you,
    Mr. Sangpo,Thimphu,Bhutan

    1. Okay, first get the total quantity. Do the following:

      1. Give input quantity a class named “item-quantity”
      2. Crete a global variable in javascript var totalQuantity = 0;
      3. On every row add or delete, do the following:
      4. var trs = document.getElementById(“tbody”).querySelectorAll(“tr”);
        for (var a = 0; a < trs.length; a++) {
            var quantity = parseInt(trs[a].querySelector(“.item-quantity”).value);
            totalQuantity += quantity;
        }

      Then you can use the variable "totalQuantity" to update in database.

  7. Dear Adnan,
    Thank u so much ,, Although you have mentioned or suggested us codes for purpose requested.it would be very difficult put the code in right place for the learners like me,. Even the missing tlof comma or semicolon , code not putting in right place , will not work. So we will not be in position make the code work at all.
    Therefore we request you to include this feature in your previouse sample project either for adding or substracting qty with new qty. This would be a great resource for us.
    We anticipate that you would kindly post it .

    Thank you
    Sangpo

Comments are closed.