dongpu8935 2016-12-06 22:54
浏览 53
已采纳

php pdo动态html表单插入数组

Trying to setup dynamic html form to insert array into database with pdo. Without adding new input fields it works fine. As soon as I add fields I get errors saying that my array is empty.

PHP code:

if(isset($_POST['submit']))
{
    $items = (isset($_POST['items']) && is_array($_POST['items'])) ? $_POST['items'] : array();

    $insertStmt = $db->prepare("INSERT INTO products (prod_id, type) VALUES (:id, :name)");
    foreach ($items as $item) 
    {
        $insertStmt->bindValue(':id', $item['id']);
        $insertStmt->bindValue(':name', $item['name']);
        $insertStmt->execute();
    } 
}

jquery code:

$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".input_fields_wrap");
    var add_button      = $(".add_field_button");

    var x = 1;
    $(add_button).click(function(e)
    {
        e.preventDefault();
        if(x < max_fields)
        {
            x++; //text box increment
            $(wrapper).append('<div>Product ID<input type="text" name="items[][id]"/><br>Product Name<input type="text" name="items[][name]"/><a href="#" class="remove_field">Remove</a></div>');
        }
    });

    $(wrapper).on("click",".remove_field", function(e)
    {
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});

html code:

<form action="" method="POST">
    <div class="input_fields_wrap">
    <button class="add_field_button">Add Product</button>
    <div>Product<input type="text" name="items[][id]"></div>
    <div>Product Name<input type="text" name="items[][name]"></div>
    </div>
    <button type="submit" name="submit" class="inner">Save workout</button>
</form>

UPDATE:

Since arrays don't allow same key I changed my javascript.

$(wrapper).append('<div>Product ID<input type="text" name="items['+x+'][id]"/><br>Product Name<input type="text" name="items['+x+'][name]"/><a href="#" class="remove_field">Remove</a></div>');

Also the form inputs.

<div>Product<input type="text" name="items[0][id]"></div>
<div>Product Name<input type="text" name="items[0][name]"></div>
  • 写回答

1条回答 默认 最新

  • dongzinen1061 2016-12-07 00:42
    关注

    By default, php put anonymous arrays of inputs into separated items, that's the reason for what you post 2 inputs with id and name and php interprets it as an array of 4 items, thus your foreach will loop 4 times instead of 2, and you will never be able to catch id and name in the same loop.

    The best solution is to put and number for each input group, like:

    items[0][id]
    items[0][name]
    
    items[1][id]
    items[1][name]
    

    See this post for further info: How to POST data as an indexed array of arrays (without specifying indexes)

    But, there's an other way to achive what you want without defining the index numbers, it only requires that you invert you arrays in inputs names like this:

    from: items[][id] to: items[id][]

    and from: items[][name] to: items[name][]

    and your php should be:

    if(isset($_POST['submit']))
    {
        $items = (isset($_POST['items']) && is_array($_POST['items'])) ? $_POST['items'] : array();
    
        $array_ids = $items['id'];
        $array_names = $items['name'];
        $array_items = array_combine($array_ids, $array_names);
    
        $insertStmt = $db->prepare("INSERT INTO products (prod_id, type) VALUES (:id, :name)");
        foreach ($array_items as $id => $name) {        
            $insertStmt->bindValue(':id', $id);
            $insertStmt->bindValue(':name', $name);
            $insertStmt->execute();        
        }
    }
    

    that way you create two arrays, one containing only the ids and one containing only the names, and then you combine them to one array that puts id on key and name on value. With that, you can do your foreach and retrieve the id and name on one loop.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 写一个bat,根据文件前缀创建文件夹,并将文件移动到对应前缀名称的文件夹内
  • ¥15 数据库原理及应用上机练习题
  • ¥30 征集Python提取PDF文字属性的代码
  • ¥15 如何联系真正的开发者而非公司
  • ¥15 有偿求苍穹外卖环境配置
  • ¥15 代码在keil5里变成了这样怎么办啊,文件图像也变了,
  • ¥20 Ue4.26打包win64bit报错,如何解决?(语言-c++)
  • ¥15 clousx6整点报时指令怎么写
  • ¥30 远程帮我安装软件及库文件
  • ¥15 关于#自动化#的问题:如何通过电脑控制多相机同步拍照或摄影(相机或者摄影模组数量大于60),并将所有采集的照片或视频以一定编码规则存放至规定电脑文件夹内