BradG
BradG

Reputation: 740

Nested while loop issue, second one loops only once and stops

I have coding issue that I am unable to resolve myself so need your help.

I have two queries fetching data from the same table:

$rs_main_model gets all unique models using GROUP BY

$rs_variant gets all models with their respective options, i.e. all columns from the table.

What I am doing is to run a while loop to list all unique models - $rs_main_model and then inside the same div run second loop to list all matching models from $rs_variant:

<?php while (!$rs_main_model->EOF)   { ?>                   
        <div>               
            <div>        
                <h2<?php echo $rs_main_model->fields['model']; ?></h2>
            </div>                                    
            <div>      
                      <?php while (!$rs_variant->EOF) { ?>           
                      <?php echo $rs_variant->fields['variant']; ?>
                      <?php $rs_variant->MoveNext(); } ?>
                </div>
        </div>
  <?php $rs_main_model->MoveNext(); } ?>

Below is an example of the actual and desired output:

The output should look something like this: |  However what I end up with is this:    

    Model A    Model A - Variant1           |  Model A    Model A - Variant1   
               Model A - Variant2           |             Model A - Variant2  
               Model A - Variant3           |             Model A - Variant3  
    Model B    Model B - Variant1           |  Model B                    
    Model C    Model C - Variant1           |  Model C          
               Model C - Variant2           |

What changes should I make to the while loops to make this work? Thank you!

Upvotes: 0

Views: 124

Answers (1)

geoandri
geoandri

Reputation: 2428

You should update the $rs_variant results on every iteration inside the outer loop by using as condition the $rs_main_model->fields['model']. Try the following

<?php while (!$rs_main_model->EOF)   { ?>                   
    <div>               
        <div>        
            <h2<?php echo $rs_main_model->fields['model']; ?></h2>
   <?php $sql_variant = "SELECT * FROM tbl_catalog WHERE model_body = '".$rs_main_model->fields['model_body']."'"; $rs_variant = $db -> Execute($sql_variant); ?>
        </div>                                    
        <div>      
                  <?php while (!$rs_variant->EOF) { ?>           
                  <?php echo $rs_variant->fields['variant']; ?>
                  <?php $rs_variant->MoveNext(); } ?>
            </div>
    </div>
<?php $rs_main_model->MoveNext(); } ?>

Upvotes: 1

Related Questions