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.

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!