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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵