gpt4 book ai didi

php - 如何将表单输入数组放入PHP数组但不是空字段

转载 作者:行者123 更新时间:2023-11-29 07:50:10 24 4
gpt4 key购买 nike

我有一个类似于下面的表单,它发布到同一页面,用户可以使用 jquery 动态添加更多文本框。

        <h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><a href="#"><span> Click to Add </span></a></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>

一切正常,但如果有人添加更多文本框并将某些文本框保留为空,那么它将提交。这是我的问题,我不想在表中提交空文本框,我想要服务器端解决方案。

这是我的完整 php 代码

<body>
<?php
if ( isset($_POST['submit_order']) ) {
if ( !empty($_POST['Product']) && !empty($_POST['Quantity']) ) {
$product = ($_POST['Product']);
$quantity = ($_POST['Quantity']);
foreach ($product as $id => $value) {
$products = ($product[$id]);
$quantitys = ($quantity[$id]);
$query = mysql_query("INSERT iNTO myorders (product,quantity) VALUES ('$products','$quantitys')", $connection);
}
}
echo "<i><h2><stront>" . count($_POST['Product']) . "</strong> Entry Added </h2></i>";
mysql_close();
}
?>
<?php
if (!isset($_POST['submit_order'])) {
?>
<h1> Add Your Order </h1>
<form method="post" action="">
<p id="add_field"><a href="#"><span> Click to Add </span></a></p>
<div id="container">
<input type="text" class="pid" id="' + counter + '" name="Product[]" />
<input type="text" class="qid" id="' + counter + '" name="Quantity[]" /><br />
</div><br />
<input type= "submit" Name="submit_order" value="Submit">
</form>
<?php }
?>
</body>

最佳答案

您可以使用array_filter来获取数组中不为空的元素。如果非空元素的数量与原始数组大小不同,则用户将某些字段留空。

$filled_product = array_filter($product);
$filled_quantity = array_filter($quantity);
if (count($filled_product) < count($product) || count($filled_quantity) < count($quantity)) {
// Report error because of unfilled fields
}

关于php - 如何将表单输入数组放入PHP数组但不是空字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26692918/

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