I have a dynamic table form input form which you can add/remove rows as you like. As someone who doesn’t have much experience, I’m stuck on how to save those input into the mySQL database.
Here’s what the input.php looks like
<form action="insert.php" method="post"> <div class="box-body no-padding"> <table class="table table-bordered"> <tr> <th>Item</th> <th>#</th> <th>Qty</th> <th>Price</th> <th>Total</th> <th></th> </tr> <tr> <td><input type="text" id="item" name="item"></td> <td><input type="text" id="no" name="no"disabled></td> <td><input type="number" id="qty" name="qty"></td> <td><input type="number" id="price" name="price"></td> <td><input type="number" id="total" name ="total" disabled></td> <td><button type="button" class="remove-row"><i class="fa fa-trash"></i></button></td> </tr> </table> </div> <div class="box-body"> <div class="button-group"> <a href="javascript:void(0)" class="add-row"><i class="fa fa-plus-circle"></i> Add Item</a> </div> </div> <div class="box-footer"> <div class="button-group pull-right"> <button type="submit" class="btn btn-default">Cancel</button> <button type="submit" class="btn btn-primary">Save</button> </div> </div> </form>
And here is the JS (jQuery) code that I use to add/remove rows
<script type="text/javascript"> window.addEventListener('DOMContentLoaded', function(){ $ (document).ready(function(){ $ (".add-row").on('click', function(){ var item = "<td><input type='text' id='item'></td>"; var no = "<td><input type='text' id='no' disabled></td>"; var qty = "<td><input type='number' id='qty'></td>"; var price = "<td><input type='number' id='price'></td>"; var total = "<td><input type='number' id='total' disabled></td>"; var remove_button ="<td><button type='button' class='remove-row'><i class='fa fa-trash'></i></button></td>"; var markup = "<tr>" + item + no + qty + price + total + remove_button + "</tr>"; $ ("table").append(markup); }); $ (".table").on('click', '.remove-row', function(){ $ (this).closest("tr").remove(); }); }); }); </script>
Here’s what the page looks like:
insert.php
<?php $ connection = mysql_connect("localhost", "root", ""); $ db = mysql_select_db("db", $ connection); if(isset($ _POST['submit'])){ $ item = $ _POST['item']; $ no = $ _POST['no']; $ qty = $ _POST['qty']; $ price = $ _POST['price']; $ query = mysql_query("insert into table(item, no, qty, price) values ('$ item', '$ no', '$ qty', '$ price')"); } ?>
I know the insert.php won’t work for my case because I need to input it as arrays. The thing is:
1. I don’t know how to implement the front end so I won’t have duplicate id/names when I click “Add Item”
2. I don’t know how to insert the arrays (that I don’t know to create) to the mysql.
Solutions with coding example will be pretty much appreciated.