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′]