gpt4 book ai didi

javascript - 如何使用foreach循环在mysql表中插入一个静态值和多个动态值?

转载 作者:行者123 更新时间:2023-11-29 06:53:31 25 4
gpt4 key购买 nike

在我的表单中,我有一个名为 Product 的字段和一个名为 Add new 的按钮,用于在每次点击时添加 2 个名为 Weight 的字段, 单价。现在,我如何使用 php 在我的 mysql 表中INSERT此表单的值?如何为重量单价值的每个输入循环产品值?

这是我想要实现的目标的示例:产品具有一个值大米和2组重量单价 值分别为 10, 5020, 45。循环 Rice 2 次的 php 部分是什么,因为 Available optionssql 中有 2 组输入INSERT值到mysql表(结构如下所述)?

Sample

MySQL表结构为:

CREATE TABLE IF NOT EXISTS `product_table` (
`ID` int(11) NOT NULL,
`product_name` varchar(30) NOT NULL,
`weight` int(10) NOT NULL,
`price` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;

此处,ID 是PRIMARY KEY,并设置为AUTO_INCRMENT

这是表单的 jqueryhtml 部分:

$(document).ready(function() {
var wrapper = $(".input_fields_wrap");
var count = 0;

$('p#add_field').click(function(e) {
e.preventDefault();
count += 1;
$('#container').append(
'<div>\n\
<label>Weight</label><input type="text" id="weight_' + count + '" name="weight[]' + '"/>\n\
<label>Unit price</label><input type="text" id="price_' + count + '" name="price[]' + '"/>\n\
<a href="#" class="remove_field">Remove</a><br>'
);
});

$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="POST">
<label>Product</label><input type="text" id="product" name="product"><br>
<div id="container" class="input_fields_wrap">
<label>Available options:</label>
<div>
<p id="add_field"><button type="button" href="#"><span>Add new</span></button></p>
</div>
</div>
<button type="submit" name="btnSubmit">Save to database</button>
</form>

这是示例fiddle 。要使该表单正常运行,PHP 操作代码应该是什么?

最佳答案

您好,您可以在 PHP 中使用以下代码

<?php
for($ri=0; $ri<count($_POST["weight"]); $ri++){
$sql = "INSERT INTO product_table (product_name, weight, price) VALUES ('".$_POST["product"]."', '".$_POST["weight"][$ri]."', '".$_POST["price"][$ri]."')";

//Execute $sql in here with your connection
}

编辑

<?php
for($ri=0; $ri<count($_POST["weight"]); $ri++){
$sql = "INSERT INTO product_table (product_name, weight, price) VALUES ('".$_POST["product"]."', '".$_POST["weight"][$ri]."', '".$_POST["price"][$ri]."')";

if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}

关于javascript - 如何使用foreach循环在mysql表中插入一个静态值和多个动态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46580650/

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