嘗試設置動態html表單以將數組插入數據庫與pdo。 不添加新的輸入字段,它工作正常。只要我添加字段,我會收到錯誤,說我的數組是空的。php pdo動態html表單插入數組
PHP代碼:
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代碼:
$(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代碼:
<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:
因爲數組不允許我改變了相同的密鑰我的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>');
也是表單輸入。
<div>Product<input type="text" name="items[0][id]"></div>
<div>Product Name<input type="text" name="items[0][name]"></div>
它說你的數組是空的? 我建議在PHP的頂部嘗試'var_dump($ items)'來查看數組是否按照您期望的方式來到 – Joundill
@Joundill Error1:未定義索引:名稱Erro2:完整性約束違規:1048列'name'不能爲null''insertStmt-> bindValue(':name',$ item ['name']);' – mypoint
數組通過vardump傳入。 – mypoint