简体   繁体   中英

Multiple html drop down with values from database using while loop

i already have a while loop that displays select inputs in my form depending on how many passengers the user is booking. Each drop down was supposed to show all data from a column in my database. The problem is that only the first drop down displays the data i fetched which is seats 1 to 30.

Query to get the airline id of the current flight

  $result = mysqli_query($conn,"select *  from flight_seat_status where flight_number = '$_SESSION[departure]'");

Variables i used to start the counting in the loop

  $print = 1;  $name = 0;

My while loop with the problem

  echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
    while($print <= $_SESSION['passengers']){
    echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
    echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;'   name = 'passengers[]'>";
    while($row = mysqli_fetch_assoc($result)){
    echo "<option value='".$row['seat_id']."'>".$row['seat_number']."</option>";
      }
    echo "</select><br>";
      $print++;
      $name++;
     }

it is able to print out a number of drop downs depending on the user but only the first drop down contains the data.

what is wrong with my code? please explain

Please use below code. All the seats records you have to fetch once outside passenger loop and store in another array and then you have to use seats array inside the passenger loop each time.

echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
$seats = [];
while($row = mysqli_fetch_assoc($result)){
    $seats[] = $row;
}
while($print <= $_SESSION['passengers']){
    echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
    echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;'   name = 'passengers[]'>";
    foreach($seats as $res_seat){
        echo "<option value='".$res_seat['seat_id']."'>".$res_seat['seat_number']."</option>";
    }
    echo "</select><br>";
    $print++;
    $name++;
}

You have to set the pointer back to 0 for using the result again

 // set the pointer back to the beginning
    mysqli_data_seek($result, 0);
    while($row = mysqli_fetch_assoc($result)){
     // do whatever here...
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM