0

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>
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
mypoint
  • 73
  • 2
  • 9
  • Which line is it saying your array is empty on? I suggest trying `var_dump($items)` at the top of your PHP to see if the array is coming through the way you expect – Joundill Dec 06 '16 at 23:01
  • @Joundill Error1: Undefined index: name Erro2: Integrity constraint violation: 1048 Column 'name' cannot be null' `$insertStmt->bindValue(':name', $item['name']);` – mypoint Dec 06 '16 at 23:16
  • Array is coming through with vardump. – mypoint Dec 06 '16 at 23:26

1 Answers1

1

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.

Community
  • 1
  • 1
leoap
  • 1,684
  • 3
  • 24
  • 32
  • Thank you! It works, except the issue if the keys for array combine ar the same. If I want to input: `[1] => keyboard [1] => case [2] => speaker` It will only input `[1] => case` – mypoint Dec 07 '16 at 10:03