Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

nested while loops

Status
Not open for further replies.

TheDust

Programmer
Aug 12, 2002
217
US
I am iterating through a query's result using a WHILE loop. Then, inside of that, I want to iterate through the rows of data from ANOTHER query's results, but as is it will only run that nested WHILE loop once and skip it on the next passings. It looks like this:

while ($row = mysql_fetch_assoc($results)) {
### stuff ###
while ($row2 = mysql_fetch_assoc($results2)) {
### stuff ###
}
### stuff ###
}

Anyone know why after the first iteration through, the nested loop is skipped over?
 
It should not. There is something wrong in your code. For example: are you sure you are not using the same variable for the two queries (perhaps an intermediate variable used to create $row and $row2?).
Gaetano
 
Because you have already iterated through all the records in the resultset, there are no more records to fetch the second time. //Daniel
 
...of course, the second query must be included inside the WHILE loop (not before it), so it is run for every $row.

Gaetano
 
I'd wager a different guess, but you haven't given us all the information...

you say (with some editing
### stuff0 ###
while ($row = mysql_fetch_assoc($results)) {
### stuff1 ###
while ($row2 = mysql_fetch_assoc($results2)) {
### stuff2 ###
}
### stuff3 ###
}


now, for your nested looping to make any sense,
### stuff1 ###

should include a line saying something like
$results2 = mysql_query($query);

if it doesn't, then ### stuff0 ### and ### stuff3 ### must

If neither of those is the case, then the problem is as danielhozac said, and you probably just need to put the pointer back to the beginning of the recordset.

If one of those is the case, then I'd say sleipnir hit the nail on the head, but that shouldn't be a problem, in that case your program should correctly not iterate over the second set.

-Rob
 
Yup, skiflyer hit it on the head here. Pretty easy fix, but then, I've been out of PHP for 3 or 4 months now... gotta shake some of this rust off. Thanks a lot guys! Peace.

Respect,
Dust
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top