Warren Haskins
Warren Haskins

Reputation: 67

Echo each Category from a table into its own DIV

My problem seems complex to me, but im sure theres a simple way to do this.

Essentially, I have a treatments list. On the MYSQL table the list's items are broken up by category, title, description and price.

I need to echo out each category into a div each, sectioning them off. So, if the user has 4 catagories of items then I should have 4 divs with all the items from each category in each.

I cant call on a cataogory directly, because the category names are what ever the user sets them to.

Is there a way to do this? Possibly even a while inside a while with PHP?


@Kaaviar Table column names are in order - Category, Title, Description, Price

@sAc - This is the basic of what im using at the moment, but this just lists everything in order of Category.

  <?php

    include 'config.php';

    $treatments = MySQL_query("SELECT * FROM treatments ORDER BY category") or die (MySQL_error('woops') ); 

    while($list = MySQL_fetch_array($treatments)) {

   echo $list['title'];
   echo $list['description'];
   echo $list['price'];


    } 

    ?>

@Luke - Your code returns nothing here on my end, with the necessary edits etc.

Thanks, Warren

Upvotes: 0

Views: 174

Answers (1)

Luke
Luke

Reputation: 3353

You can try the below, obviously you dont have to use the markup I have demo'ed.

$string = '<div><ul>';
$cat = '';
while ($row = mysql_fetch_assoc($result)) {
  if ($row['category'] != $cat && !empty($cat)) {
    $string .= '</ul></div><div><ul>';
  }
  $string .= '<li>' . $row['title'] . '</li>';
  $cat = $row['category'];
}
$string .= '</ul></div>';

Hope it helps

Luke

Upvotes: 1

Related Questions