How to add & delete rows dynamically using php and javascript

15/04/2017   03:56:50 PM

Hello, in this tutorial I will explain how to Add & Delete Rows Dynamically Using php.Here, we have created a table and initially add one row in it. This row can contain any input. Now there is button called “Add more”. When user clicks on that button a new row will add below that current row with desired input format. This process will repeat to add several number of rows.

1) Creating Database Table

  • First create a database then create table inside your database. I have created a sampledb database inside registration table created as you can see in the below image.

add_delete_rows_dynamically_php_jquery_javascript

 

2) Create index.php page

<script type="text/javascript" src="jquery-latest.js"></script>

<script type="text/javascript">

jQuery(document).ready(function($){

$('.my-form .add-box').click(function(){

var n = $('.text-box').length + 1;

if( 9 < n ) {

alert('Stop it!');

return false;

}

var box_html = $('<p class="text-box"><label for="box' + n + '"><span class="box-number">' + n + '</span></label><input type="text" name="name[]" required="required" placeholder="Enter Mobile Name" value="" id="box' + n + '" /><input type="text" required="required" name="price[]" placeholder="Enter Price" value="" id="box' + n + '"/><a href="#" class="remove-box"><img src="images/delete.png" style="height:25px; width:20px;"></a></p>');

box_html.hide();

$('.my-form p.text-box:last').after(box_html);

box_html.fadeIn('slow');

return false;

});

$('.my-form').on('click', '.remove-box', function(){

// $(this).parent().css( 'background-color', '#FFFFFF' );

$(this).parent().fadeOut("slow", function() {

$(this).remove();

$('.box-number').each(function(index){

$(this).text( index + 1 );

});

});

return false;

});

});

</script>

<form method="post" name="frm" action="save.php">

<input type="submit" name="save" value="Save" /><br />

<br />

<div class="row" id="div1">

<div class="my-form">

<p class="text-box">

<b>1 </b>

<input type="text" name="name[]" required="required" placeholder="Enter Mobile Name" value="" id="box1"   />

<input type="text" name="price[]" required="required" placeholder="Enter Price" value="" id="box' + n + '" />

<a class="add-box" href="#"><img src="images/sq_plus.png" style="height:25px; width:20px;"></a><br />

</form>

</p>

</div>

</div>

 

3) Create save.php page

<?php

$name=$_POST['name'];

for($i=0;$i<sizeof($name);$i++){

$price=$_POST['price'];

$conn = new mysqli("localhost", "root", "", "sampledb");

$sql = "INSERT INTO product (name, price)

VALUES ('$name[$i]', '$price[$i]')";

if ($conn->query($sql) === TRUE) {

echo "";

} else {

echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

}

header('location:index.php');

?>


Output

                   

Support us by Sharing