Jump to content

Best way to code loops to display data - noob


JohnHall35

Recommended Posts

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
Share on other sites

<?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
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.