gpt4 book ai didi

php - 如何在php中循环遍历多个动态输入字段以将它们插入到mysql表中?

转载 作者:行者123 更新时间:2023-11-29 10:36:18 25 4
gpt4 key购买 nike

我的 mySql 数据库中有一个名为 item 的表,其中包含名为 itemprice 的列。通过 jquery,我使用了一个按钮来生成用于输入多个商品及其价格的字段。但是,用于循环输入以分别插入它们的 php 代码应该是什么? (例如商品 1价格 1)像这样的事情 that I'm trying to achieve

<script>
$(document).ready(function() {
var count = 0;

$('p#add_field').click(function(e) {
e.preventDefault();
count += 1;
$('#container').append(
'Item: <input type="text" id="item_' + count + '" name="item[]' + '"/>\n\
Unit price: <input type="text" id="price_' + count + '" name="price[]' + '"/><br>'
);
});

});
</script>

<?php
if (isset($_POST['btnSubmit'])) {
if ($_POST['item']) {

foreach ($_POST['item'] as $key => $value) {
$sql_item = sprintf("INSERT INTO item (item) VALUES ('%s')", mysql_real_escape_string($value));
$result_item = $db->query($sql_item);
}
}
echo "<h1>User Added, <strong>" . count($_POST['fields']) . "</strong> item(s) added for this user!</h1>";
$db->kill();
}
?>
<?php if (!isset($_POST['btnSubmit'])) { ?>
<form action="" method="POST">
<div id="container">
<label>Available items</label>
<p id="add_field"><button type="button" href="#">Add new item</button></p>
</div>
<button type="submit" name="btnSubmit">Save items</button>
</form>
<?php } ?>

最佳答案

您的数据存储异常,请更改item表,使其具有自动增量ID列和item name商品价格列。

更改 foreach 循环中的代码以反射(reflect)表更改。

您清理 SQL 查询的方法不是最好的方法,您正在使用 mySQLi 连接到数据库,因此使用类的内置函数 prepare and execute queries .

关于php - 如何在php中循环遍历多个动态输入字段以将它们插入到mysql表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46377239/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com