[英]How can I create multiple dropdown based on the selected values with data in it in PHP?
So I am trying to create multiple dropdown boxes that shows data from a database. 因此,我试图创建多个下拉框来显示数据库中的数据。 I am able to create multiple dropdown, but it only shows data in the 1st dropdown and not on the other created ones.
我可以创建多个下拉菜单,但是它仅在第一个下拉菜单中显示数据,而在其他已创建的下拉菜单中不显示数据。 I am new to this and would like some help from some of the pros.
我对此并不陌生,希望获得一些专业人士的帮助。 Here is the code:
这是代码:
<form action="#" method="post">
<select id="aantalMaaltijden" name="aantalMaaltijden">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<input type="submit" name="submit" value="Bereken" />
</form>
<?php
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
if(isset($_POST['submit'])){
$selected_val = $_POST['aantalMaaltijden']; // Storing Selected Value In Variable
for($i=0; $i<$selected_val; $i++){
echo "<select>";
while($row = $result->fetch_array()) {
echo "<option>".$row['name']."</option>";
}
echo "</select>";
}
}
?>
Thank you :) 谢谢 :)
Change your code like this and let me know 像这样更改您的代码,让我知道
if (isset($_POST['submit'])) {
$options = "";
$selected_val = $_POST['aantalMaaltijden']; // Storing Selected Value In Variable
while ($row = $result->fetch_array()) {
$options .= "<option>" . $row['name'] . "</option>";
}
for ($i = 0; $i < $selected_val; $i++) {
echo "<select>";
echo $options;
echo "</select>";
}
}
Edited 已编辑
The issue was with $result->fetch_array()
. 问题出在
$result->fetch_array()
。 You can't call $result->fetch_array()
twice, against the same resource. 您不能针对同一资源两次调用
$result->fetch_array()
。 The resource result you pass in to $result->fetch_array()
is done by reference. 您传递给
$result->fetch_array()
的资源结果是通过引用完成的。 You'll need to reset the position of the pointer before you can use $result->fetch_array()
a second time. 您需要重新设置指针的位置,然后才能
$result->fetch_array()
使用$result->fetch_array()
。 That's why your 1st dropdown gets filled with data not others. 这就是为什么您的第一个下拉列表填充的是数据而不是其他数据。
Since, all your dropdowns consist same options, I added all the options in the variable $options
and the same concatenated in all select
. 由于所有下拉菜单都包含相同的选项,因此我在变量
$options
添加了所有选项,并在all select
中将其串联在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.