JohnHall35 Posted March 22, 2011 Share Posted March 22, 2011 Hi, I'm trying to fetch rows of data from a mysqli table and display them in the browser in categories. I have the while loop working fine, but I want to break the results down into categories, instead of one big list sorted by a field using ORDER BY. So for example, let's say I have a database table containing people's names, email address, phone numbers, etc. and I want to display them in the browser in separate tables by the city in which they live (each city name would be a h1 or h2 tag) and the appropriate rows would be displayed under each heading, sorted by the person's name. I can do it by using multiple while loops, separating each city into it's own array and then repeating my html table code a bunch of times, but I know there has to be a much cleaner way. Can anyone point me in the right direction? Thanks! Link to comment https://forums.phpfreaks.com/topic/231378-best-way-to-code-loops-to-display-data-noob/ Share on other sites More sharing options...
PFMaBiSmAd Posted March 22, 2011 Share Posted March 22, 2011 <?php // execute your query here to get the rows you want in the order that you want them $last_heading = null; // variable to remember the last heading while($row = your_fetch_assoc()_statement){ // detect a change in the heading value and output the new heading/start a new section if($last_heading != $row['your_heading_column_name']){ // detect if it is not the first heading - close out the previous section if($last_heading != null){ // your code to close the previous section/table... echo "close section<br />"; } // output the new heading/start a new section here... echo "new section title - {$row['your_heading_column_name']}<br />"; // remember the new heading value as the last_heading $last_heading = $row['your_heading_column_name']; } // output the actual data here... echo "data - {$row['your_data']}<br />"; } // if there was any output - close out the last section if($last_heading != null){ // your code to close the previous table... echo "close section<br ?>"; } ?> The 'your_heading_column_name' in the above sample code would be your 'city' column name. Link to comment https://forums.phpfreaks.com/topic/231378-best-way-to-code-loops-to-display-data-noob/#findComment-1190776 Share on other sites More sharing options...
JohnHall35 Posted March 22, 2011 Author Share Posted March 22, 2011 Works great - thanks so much! Link to comment https://forums.phpfreaks.com/topic/231378-best-way-to-code-loops-to-display-data-noob/#findComment-1190790 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.