I'll try and tackle this in two ways, without having all of your other code and your database at my end it is very difficult to debug all of that code, it's very confusing.
I've pasted here my attempt to sort it out, I've tried to do as little as possible to your code, as such, I haven't re-written it, just patched up a little. This means that this code may not run straight off, I may have made a few typos here and there, remember, I couldn't test this, I had to debug it in my head.
The problem has arisen because of two things, the amount of code / number / complexity of loops and overwriting variables.
Imagine this
loop
loop
loop
loop
If you are nesting loops like this, think from the bottom up, the first time the last loop is reached, it will itterate until the condition is met, it will then move to previous loop and itterate that and so on. It's very important to use different variable names for all your loops, so if you execute $query in the top part of the loop, you can't use that again otherwise the $query value will have changed for the next itteration of the first loop. You also have to be 100% sure you don't reset a variable value with assignment, you may find it easier to initialise all variables at the top of the page;
$var = '';
$var2 = '';
Then make sure you are using .= and not =. This as you mentioned earlier is concatenation.
The better solution to this code is to work with database joins, from looking at your code it's needlessly complex, most of this information could be pulled from a LEFT JOIN on the required tables. You should look at the mySQL docs and maybe try re-writing the code. You would end up with something like this
$query = 'SELECT field1,field2,field3,field4,field5,field6 FROM table LEFT JOIN table2 ON (table.primary_id = table2.foreign_id) LEFT JOIN table3 ON (table.primary_id = table3.foreign_id) LEFT JOIN table4 ON (table.primary_id = table4.foreign_id);l
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo $row['field1'];
echo $row['field2'];
echo $row['field3'];
echo $row['field4'];
echo $row['field5'];
echo $row['field6'];
}
Anyway, I've posted your code in the next post, hopefully it will be OK but it may need some adjustment.
Andrew