user1479891
user1479891

Reputation: 149

Looping through a query into separate tables

I call my query ok

    $sql = "Call new_c02(1,1,'2014-01-10','2014-01-10')";
    if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
    }

and it generates a table thus:

Acc  Data1  Data2  Data3    
1    x     y     z
1    a     b    c
2    x     y    z
2    a     b    c

I can throw this into a table using

<table> <?php while($row = $result->fetch_assoc()){ ?>                  
<tr>
  <td>
  <?php    echo $row['accounts'] . '<br />'; ?>
  </td>
</tr>
</table>

etc etc

However I would like to be able to generate a separate table for every different account so i have a table for Acc 1 and a separate table below it for Acc2 and so on until I am exhausted of Accs in the query. Just not sure how to loop through the query to make a separate table for each

Help really appreciated Simon

Upvotes: 0

Views: 65

Answers (1)

scrowler
scrowler

Reputation: 24406

You'll need to keep track of which Acc numbers you've output already, and if the current one hasn't been output, create a new table. Something like this should do the trick:

<?php
$acc_output = array();
$is_first = true;
while($row = $result->fetch_assoc()) {

    // set this according to your array structure            
    $acc_id = $row['accounts']['Acc']; 

    // if this is the first row, open a table
    if($is_first)
        echo '<table>';

    // if it's not the first row, and it is a new acc ID
    // close current table and open a new table
    if(!$is_first && !in_array($acc_id))
        echo '</table>' . PHP_EOL . '<table>';

    // add current acc_id to the array
    $acc_output[] = $acc_id;
    // set not first
    $is_first = false;

    ?>
    <tr>
      <td>
      <?php    echo $row['accounts'] . '<br />'; ?>
      </td>
    </tr>

    <?php

}

// then, close the last table
?>
</table>

To use your example data in a test case:

Acc  Data1  Data2  Data3    
1    x     y    z       - is_first, open new table
1    a     b    c       - not first, is in array - do nothing        
2    x     y    z       - not first, not in array - close/open new table
2    a     b    c       - not first, is in array - do nothing
- end, close table

Upvotes: 1

Related Questions