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 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数