Jump to content

groupt records by category and splitting with sub-headings


adambedford

Recommended Posts

So I've got a nice and straight forward query and a table that has several fields, including 'category'. I'm repeating the results of the query on the page (with a basic while loop) but I want to split the records up by category.

 

Now I know I can use the MySQL GROUP BY option to group the records together, but I don't know how to actually split the records and add a subheading before repeating the records in that category. The subheader content will come will be the 'category' field but I really don't know how to figure this out. Is it even possible?

 

I know I could do it with a separate query for each category and use a WHERE clause but that seems awfully long winded and I'm certain there must be a better solution!

 

Any help would be really appreciated. Thanks!

1st order query by category

2nd set variable $curent_cat to something that can be category

3rd when browse records check varijable $curent_cat again category in record and if it diferent echo subhead and set $curent_cat to category from record

out of if block echo rest of data

 

hi there, thanks for your reply! I'm afraid I don't quite understand what to do, however! I'm still getting to grips with PHP.

 

My database schema is as follows:

 

table: tracks

fields: t_ID, t_Name, t_Description, t_Category, t_Filepath.

 

My query is simply "SELECT * FROM tracks". So would I change it to: "SELECT * FROM tracks ORDER BY t_Category ASC"?

 

Would you please mind explaining the 2nd and 3rd steps? I don't quite understand what you mean 'set variable $curent_cat to something that can be category' and 'browse records check variable $curent_cat again'.

 

Thank you!

//query database
$cur_cat='';
while($row = ...){
      if($row['t_Category'] != $cur_cat){
            echo $row['t_Category'];
            $cur_cat = $row['t_Category'];
     }
     // echo rest of data
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.