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!

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

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.