gpt4 book ai didi

javascript - 动态发票表单字段并发布到数据库

转载 作者:行者123 更新时间:2023-12-03 06:24:08 24 4
gpt4 key购买 nike

我正在构建一个表单来创建发票。目前它的表单字段为:

产品名称、数量。

我有一个“添加更多”按钮,可以添加上述表单字段的另一行。

然后它作为数组提交到另一个 php 页面。我遇到的问题是将每个关联的表单字段相互匹配,因为当我将其保存在数据库中时,我需要正确的产品名称、数量显然位于表中的同一行。只是不知道如何匹配它们。

目前我在表单字段页面上的代码是:

<html>  
<head>
<title>Invoice Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<h2 align="center">Invoice Test</h2>
<div class="form-group">
<form name="submit" id="submit" action="name.php" method="POST">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td>
<td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" placeholder="Product Name" class="form-control name_list" /></td><td><input type="text" name="qty[]" placeholder="QTY" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
});
</script>

在表单提交到的 name.php 页面上。从数组中获取每个产品和关联数量并将其放入数据库行的最佳方法是什么?请记住,这是动态的。

在 name.php 上,当我打印出 $_POST 时,我当前有这个数组结构:

Array
(
[product_name] => Array
(
[0] => test1
[1] => test2
[2] => test3
[3] => test4
)

[qty] => Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)

[submit] => Submit
)

我猜我需要计算键的数量,然后在数组的另一个维度中匹配它们。只是不确定这是否是最好的方法,甚至不确定如何做到这一点。

最佳答案

你可以使用这个

$productName = $_POST['productName'];
$qty = $_POST['qty']

foreach($productName as $key => $productName) {
$productQty = $qty[$key];

//Use your ORM (or whatever) to inster into DB
//$productName and $productQty

}

编辑

或者,更好的是,您可以使用 PHP 的 array_combine:

$productName = $_POST['productName'];
$qty = $_POST['qty']

$arryWithTotals = array_combine($productName, $qty);

foreach($arrayWithTotals as $productName => $productQty) {
//insert into DB
}

关于javascript - 动态发票表单字段并发布到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38722557/

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