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>