Adding rows to mysql from dynamic jquery form fields

我只是一个虾纸丫 提交于 2019-12-11 08:09:04

问题


please excuse me as I am not proficient in php/mysql. I have an html form for inventory. I have a set of fields to update my sql database, they are item_name, item_cost, item_quantity. I have a jquery button that allows the user to dynamically add additional items/rows.

Question: how can I have php loop whatever number of items the user adds and put them in the mysql database?

thank you for your time.


回答1:


If you have multiple form inputs with the same name, and that name ends in double square brackets [], their values will be turned into an array when PHP populates $_POST from the form.

So your jQuery button should insert a row with fields named like this:

<input type="text" name="item_name[]" value="" />
<input type="text" name="item_cost[]" value="" />
<input type="text" name="item_quantity[]" value="" />

In your PHP code that takes the form submission, you can process all the rows that exist like this:

//I used `item_name` as the loop termination condition, 
//but any of the 3 keys would have worked
for ($i = 0; $i < count($_POST['item_name']); $i++) {
    $item_name = $_POST['item_name'][$i];
    $item_cost = $_POST['item_cost'][$i];
    $item_quantity = $_POST['item_quantity'][$i];

    //here, inside the loop, run your database query using the 3 values above    
}



回答2:


Another (hard) way is to have a hidden input box which it's value is the number of the items the users wants to submit, on each jquery "add button" clicked, also the value of the hidden input will be updated(value++), and you should do the other input names like "name_id" while you're making them with jquery, so you could get them on server side... .



来源:https://stackoverflow.com/questions/12063713/adding-rows-to-mysql-from-dynamic-jquery-form-fields

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!