-2

Possible Duplicate:
Displaying a table in PHP with repeated columns

I want to display some MySQL data in a particular structured manner. Let's say for example I have this data in MySQL Database

id         sections                 items
1          Section A                Item 1
1          Section A                Item 2
1          Section A                Item 3
1          Section A                Item 4
1          Section B                Item 5
1          Section B                Item 6
1          Section C                Item 7
1          Section C                Item 8
1          Section A                Item 9
1          Section D                Item 10
1          Section D                Item 11

How do I get it to display like this in PHP:

SECTION A
---------

Item 1
Item 2
Item 3
Item 4
Item 9


SECTION B
---------

Item 5
Item 6


SECTION C
---------

Item 7
Item 8

SECTION D
---------

Item 10
Item 11
Community
  • 1
  • 1
manlikeangus
  • 421
  • 9
  • 28

2 Answers2

2
$sql = mysql_query("SELECT sections, items 
                    FROM my_table 
                    ORDER BY sections");
$lastSection = '';
while($row = mysql_fetch_array($sql)) {
   if($lastSection != $row['sections'])
       echo $row['sections'] . '<br />';
   echo $row['items'] . '<br />';
   $lastSection = $row['sections'];
}
Mihai Matei
  • 24,166
  • 5
  • 32
  • 50
0

Try to get all data from DB ordered by "section" and display it from plain array.

<? $currentSection = null; ?>
<? foreach ($data as $row): ?>
  <? if ($row['section'] != $currentSection): ?>
    <? $currentSection = $row['section']; ?>
    <h1><?=$row['section']?></h1>
  <? endif; ?>
  <div><?=$row['item']?></div>
<? endforeach; ?>
Skpd
  • 670
  • 3
  • 17