Reputation: 907
I need multiple rooms in a form with the same dropdown menu in each row. This is my code so far:
<?php for ($i=1; $i<=$No_of_rooms; $i++) {?>
<tr class="formspace">
<td class="formleft">Room <?php echo $i ?></td>
<td>
<select name="roomtype[<?php echo $i ?>]">
<?php do { ?>
<option value="<?php echo $row_room['roomtype'] ?>"><?php echo $row_room['room type'] ?></option>
<?php } while ($row_room = mysql_fetch_assoc($room)) ;?>
</select>
</td>
</tr>
<?php }?>
The first row displays correctly but the following dropdowns are empty. It looks as though mysql_fetch_assoc has "expired" after the first run-through and doesn't work again. Obviously I don't want to repeat the mySQL query for each line, so how do I do it?
Thanks in advance...
Upvotes: 1
Views: 111
Reputation: 6346
The mysql pointer will be at the end once you loop around it once, so you either need to reset the pointer, or (a better way) would be to set the content to an array before your for loop and then loop around that array each time, for example:
<?php
$allrooms = array();
while ($row = mysql_fetch_assoc($room)) {
$allrooms[] = $row;
}
for ($i=1; $i<=$No_of_rooms; $i++) {?>
<tr class="formspace">
<td class="formleft">Room <?php echo $i ?></td>
<td>
<select name="roomtype[<?php echo $i ?>]">
<?php foreach ($allrows as $row_room) { ?>
<option value="<?php echo $row_room['roomtype'] ?>"><?php echo $row_room['room type'] ?></option>
<?php } ?>
</select>
</td>
</tr>
<?php } ?>
Also, as a sidenote. The mysql_*
functions have been officially deprecated as of PHP 5.5, and it is recommended to use mysqli or PDO moving forward. I'm not sure how easy it would be for you to convert your code into this, but it definitely should be considered. More information on this can be found on php.net in their article about choosing a MYSQL API
Upvotes: 1
Reputation: 7930
I'd suggest that you just save the MySQL result to an array first, and then loop through that repeatedly. Either that, or generate the HTML for the options once, save it as a string, and then print that into all the select boxes. They will always be identical, will they not?
Upvotes: 1