tags:

views:

38

answers:

4

Hello

I have the following code: (query added)

$weight_table = mysql_query ("SELECT * FROM ".$prefix."weight ORDER BY wlimit DESC");    
foreach ($weight as $area => $weight) {
        echo $weight;

        while ($weight_row = mysql_fetch_array($weight_table)) {
            print_r($weight_row);
            $limit = $weight_row['wlimit'];
            if ($weight < $limit) {
        $weight_level[$count] = $weight_row;
            }
        }
    }
    print_r($weight_level);

Where $weight_table is a mysql query result and $weight is an array.

My problem is that $weight_table seems to be expiring after the first while loop, so that the $weight array is effectively treated as having one item. This is a problem!

Can anyone suggest why php would forget a mysql result after the first use?

+1  A: 

You override $weight array in the foreach declaration. Use $area => $_weight instead.

fabrik
+2  A: 

The first iteration through the for loop, you're fetching all of the records from the mysql result set. Your inner while loop will run until all the rows are gone. How many rows do you want it to pull?

Also you're re-using $weight which is a bad idea and may be causing side effects.

foreach ($weight as $area => $wt) { 
   echo $wt; 

   while ($weight_row = mysql_fetch_array($weight_table)) { 
      print_r($weight_row); 
      $limit = $weight_row['wlimit']; 
      if ($wt < $limit) { 
         $weight_level[$count] = $weight_row; 
      } 
   } 

   mysql_data_seek($weight_table,0);
} 
print_r($weight_level); 
Fosco
I want to pull everything, once for each value in the $weight array. It seems to give up after the first value. Also, changed the $weight variable as above.
YsoL8
Is there anything in the php setup that could affect this? I think it was working a while ago.
YsoL8
@YsoL8: Your MySQL-query (and result) are fine?
fabrik
@fabrik The result is good. (very simple select statement)
YsoL8
Simply add mysql_data_seek($weight_table,0); after the While loop completes, so next iteration it will be back at the start.
Fosco
@fosco That has cleared the problem. (Will need to test it further of course). What does it do?
YsoL8
It resets the query result set back to the beginning so that you can fetch them all again.
Fosco
A: 
while ($weight_row = mysql_fetch_array($weight_table)) {
    print_r($weight_row);
    foreach ($weights as $area => $weight) {
        echo $weight;
       $limit = $weight_row['wlimit'];
       if ($weight < $limit) {
          $weight_level[$count] = $weight_row;
       }
   }
}
print_r($weight_level);

Use $weight array as $weights

Sadat
Switching the while and foreach loops distorts the contents of $weight_level
YsoL8
A: 
foreach ($weight as $area => $weight) {

You're overwriting what was in your $height array, which is why it is expiring after the first run through your loop. Try using another variable name for one or the other.

JCD