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()
. You can't call $result->fetch_array()
twice, against the same resource. The resource result you pass in to $result->fetch_array()
is done by reference. You'll need to reset the position of the pointer before you can use $result->fetch_array()
a second time. 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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.