从动态jquery表单字段向mysql添加行 [英] Adding rows to mysql from dynamic jquery form fields

查看:125
本文介绍了从动态jquery表单字段向mysql添加行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请原谅我,因为我不熟练的php / mysql。我有一个HTML格式的库存。我有一组字段来更新我的sql数据库,它们是item_name,item_cost,item_quantity。我有一个jquery按钮,允许用户动态添加额外的项目/行。



问题:我如何使用PHP循环任何数量的项目,用户添加并放置在mysql数据库中?



谢谢你的时间。

解决方案

如果您有多个具有相同名称的表单输入,并且该名称以双方括号 [] 结尾,则当PHP填充<$ c时,它们的值将变为数组$ c> $ _ POST 从表单。



所以你的jQuery按钮应该插入一行,这样的字段命名如下:

 < input type =textname =item_name []value =/> 
< input type =textname =item_cost []value =/>
< input type =textname =item_quantity []value =/>

在您提交表单的PHP代码中,您可以处理所有这样存在的行:

  //我使用`item_name`作为循环终止条件,
//但是3个键中的任何一个($ 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];

//这里,在循环中,使用

$ / code $

$ b运行数据库查询$ b

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.

解决方案

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    
}

这篇关于从动态jquery表单字段向mysql添加行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆