Welcome to WebmasterWorld Guest from 54.159.240.93

Forum Moderators: coopster & jatar k

While loops and mysql data seek

   
2:32 am on Apr 7, 2011 (gmt 0)



Hello everyone,

I am trying to get the results from a MySQL DB and display them in a few HTML select tags.

The first while loop runs fine, the second runs fine if I use mysql_data_seek($result, 0); but I cannot do the same trick for a third while loop and I need to have 10 of these, what is the trick for this scenario?

This is the code so far if useful at all:
<p>
<select name="brand_01">
<option selected="selected" value="<?php echo $row['brand_01']; ?>"><?php echo $row['brand_01']; ?></option>
<?php while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['cp_brand_name'].'">'.$row['cp_brand_name'].'</option>';
} ?>
</select>
</p>
<?php mysql_data_seek($result, 0); ?>
<p>
<select name="brand_02">
<option selected="selected" value="<?php echo $row['brand_02']; ?>"><?php echo $row['brand_02']; ?></option>
<?php while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['cp_brand_name'].'">'.$row['cp_brand_name'].'</option>';
} ?>
</select>
</p>


I'm pretty sure this can be done, I just don't have a clue,

Thanks
1:59 pm on May 24, 2011 (gmt 0)

WebmasterWorld Administrator coopster is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Why use data seek? If you need to "rewind" the pointer ... well, I guess I never approach it that way. I build the select elements within the same while loop construct. Iterate once over the result set, building the select containers at the same time into a variable. Echo them out afterward.
2:38 pm on May 24, 2011 (gmt 0)



Another way to do it is to add the rows from the result into an array, then loop through that array whenever you want to create the HTML element, e.g.

$my_array = array();
while($row = mysql_fetch_array($result)
{
$my_array[] = $row;
}

and then

for($i = 0; $i < sizeof($my_array); $i++)
{
echo '<option value="' . $my_array[$i]["cp_brand_name"] . '">' . $my_array[$i]["cp_brand_name"] . '</option>';
}

You can do that loop as many times as you like then without running any more MySQL queries.
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month