tags:

views:

436

answers:

3
$query1 = "SELECT * FROM idevaff_affiliates";
$affiliateID = mysql_query($query1) or die(mysql_error());

This is my query above - I would like to use it for two WHILE loops

The first one is in the header section - setting up jquery

while($row = mysql_fetch_assoc($affiliateID)){
}

The second is used in a while loop in the body

while($row = mysql_fetch_assoc($affiliateID)){
}

Why can't I get it to work? - I did get it working but had to make two queries using the same SELECT info using two different variables.

+3  A: 

Calling mysql_fetch_assoc() retrieves the next row (i.e., the next one you haven't already retrieved). Once you've retrieved all the rows, it returns false. So, once you've gotten through that first loop, you have retrieved all the rows, and all you'll get back is false every time!

If you need to reuse the same data twice, how about putting it all in an array?

$rows = array();
while($row = mysql_fetch_assoc($affiliateID)){ 
    $rows[] = $row;
}

Now you can iterate through $rows as many times as you like:

foreach($rows as $row) { ... }
VoteyDisciple
Thanks - I didn't want to keep my work around.
Kauthon
@Wizzard's suggestion of `mysql_data_seek` to rewind the result set is a better option. Among other things, it won't use up a bunch of RAM on result sets like this answer will by storing each row in memory.
ceejayoz
+4  A: 

This doesn't work because once you run through the result set once, the results internal pointer is at the end. To use it again you need to use mysql_data_seek before your second loop to reset the internal pointer to the beginning of the result set.

Wizzard
+1  A: 

You may seek the first row... using mysql_data_seek($affiliateID, 0), now you can do mysql_fetch_assoc() again... anyway, I prefer to load the result in an array.