In this example, youll learn how to insert data into MySQL table using dynamic textboxes generated by jQuery. The aim is to understand how to get array of values passed by textboxes and then finally how to insert them into respective fields in MySQL table. The following example let you know the process to generate a rows with textboxes using jQuery. Once you have submitted values the values are to be saved in MySQL table.

Steps to insert data using dynamic multiple textboxes :

In order to work out this example you need to have a table in MySQL. The following is the simple table code taken to discuss the example. You can extend fields and textboxes as per your requirement.

Step 1 : Code for Table(mytbl)

CREATE TABLE `mytbl` (
  `sno` int(11) NOT NULL,
  `name` varchar(100) NOT NULL,
  `company` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step 2 :  The following code help you to understand how to create textboxes using jQuery.

<html>
<head>
<script  src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("#buttonAdd").bind("click", function () {
        var div = $("<div />");
        div.html(GenerateTextbox(""));
        $("#TextBoxContainer").append(div);
		 $("#TextBoxContainer1").append(div);
    });
    $("#buttonGet").bind("click", function () {
        var values = "";
        $("input[name=CreateTextbox]").each(function () {
            values += $(this).val() + "\n";
        });
       // alert(values);
    });
    $("body").on("click", ".remove", function () {
        $(this).closest("div").remove();
    });
});
function GenerateTextbox(value) {
    return '<input name = "CreateTextbox[]" type="text" value = "' + value + '" /> <input name = "CreateTextbox2[]" type="text" value = "' + value + '" />   <input type="button" value="Remove" class="remove" />'
          
}
</script>	
</head>
<body>
<form action="" method="POST">
<input id="buttonAdd" type="button" value="Click here to Add Textbox" />
<br />
<br />
<div id="TextBoxContainer">
    <!--Textboxes will be added here -->
</div>
<br />
<input id="buttonGet" name="btn" type="submit" value="Show Values" />	
		</form>
</body>
</html>

Step 3 : Code to insert data submitted by above form.

<?php
$con = mysqli_connect('localhost','root','','test');
 
if(isset($_POST['btn']))
{
	$data1 = array();
	$data2 = array();
	$data1 =$_POST['CreateTextbox'];
	$data2 =$_POST['CreateTextbox2'];
	// echo count($data2);
 	// echo '<br>';
	$i = 0;
	while($i<count($data1))
	{
	 $data1[$i] . $data2[$i];
		//insert data 
		$sql = "insert into mytbl(name,company) values('".$data1[$i]."','".$data2[$i]."')";
		$result = mysqli_query($con,$sql);
		
	    $i++;
	}
	 echo "Inserted Successfully!";
	
//	print_r($data1);
	
	
}
?>