<body>
<?php
$con = mysqli_connect('localhost','root','','cash');
$query = "SELECT DISTINCT category FROM cash";
$result = mysqli_query($con,$query);
$dropDownList = '<select name="names[]"><option value = "">---Select---</option>';
while ( $d=mysqli_fetch_assoc($result)) {
$dropDownList .= "<option value='" . $d['category'] . "'>" . $d['category'] . "</option>";
}
$dropDownList .= '</select>';
?>
<script type="text/javascript">
$(document).ready(function() {
var InputsWrapper = $("#InputsWrapper");
var AddButton = $("#AddMoreFileBox");
var dropOption = <?php echo json_encode($dropDownList) ?>;
var x = InputsWrapper.length;
var FieldCount = 1;
$(AddButton).click(function(e)//on add input button click
{
FieldCount++;
$(InputsWrapper).append('<tr><td>'+dropOption+'<td><input type="text" name="cate[]" id="categ"/></td><td><input type="number" name="money[]" id="amount"/></td></tr>');
x++;
return false;
});
});
</script>
<form action="selectxpprocess.php" method="post">
<table id="InputsWrapper" >
<tr>
<span class="small"><a href="#" id="AddMoreFileBox" class="btn btn-info">Add More Field</a></span>
</tr>
<tr>
<td><label for='names[]'>Category:</label></td>
<td><label for='cate[]'>New Category:</label></td>
<td><label for='money[]'>Amount:</label></td>
</tr>
<tr>
<td><?php echo $dropDownList?></td>
<td><input type="text" name="cate[]" id="categ"/></td>
<td><input type="number" name="money[]" id="amount"/></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
这是我的第一页。我有一个按钮,当你点击它时会弹出另一个Dropdown,文本框和数字输入。我想要的条件是如果在下拉列表中没有选择任何内容,则从文本框中获取数据。之后将相应的金额值传递给数据库。
<?php
$con = mysqli_connect('localhost','root','','cash');
if($_POST['names'] != '' && $_POST['cate'] == '') {
foreach($_POST['names'] as $catego) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}
}else {
foreach($_POST['cate'] as $categ) {
foreach($_POST['money'] as $amo){
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$categ."','".$amo."')");
}
}
}
$_POST=array();
mysqli_close($con);
header("Location: selectxp.php");
exit;
?>
答案 0 :(得分:1)
自$_POST['names']
&amp; $_POST['cate']
是数组,您可以将它们作为字符串检查,即。 if($_POST['names'] != '' && $_POST['cate'] == '')
。此外,您正在嵌套循环,而您需要通过数组键链接它们。像 -
foreach($_POST['names'] as $key => $val){
if($_POST['names'][$key] != '' && $_POST['cate'][$key] == '') {
$catego = mysqli_real_escape_string($con,$_POST['names'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
else {
$catego = mysqli_real_escape_string($con,$_POST['cate'][$key]);
$amo = mysqli_real_escape_string($con,$_POST['money'][$key]);
mysqli_query($con,"INSERT INTO cash (category, amount) VALUES ('".$catego."','".$amo."')");
}
}