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!

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

//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
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.