Jump to content

Printing US States & Listings For Each State


codeline

Recommended Posts

I've got 2 database tables (states, stores) and I want to output all the states with a list of specific locations under each state.

 

My 'states' table has a 'state_id' and 'state' while my 'stores' table has all the store information along with the 'state_id' to work with the 'states' table.

 

How would I ago about formulating a loop to display all locations organized by each state, etc.?

Write your query to get all the information, first. Then,

 

1. Before the loop, start with a previous state = nothing

2. Inside the loop, compare the current state with the previous state. If they don't match,

2a. If there was a previous state at all, close a table or do whatever

2b. Start a table or do whatever

2c. previous = current

3. Display the store

4. After the loop, close the table or do whatever

Hi

 

Basics like this:-

 

<?php

$query = mysql_query ("SELECT * FROM states a LEFT OUTER JOIN stores b ON a.state_id = b.state_id ORDER BY a.state");

// Starts the loop for fetching the records of the previous query.
$prevState = "";
while($row = mysql_fetch_array($query))
{
if ($prevState != $row['state'])
{
	$prevState != $row['state']
	echo "New State $precState<br />";
}
echo "Store Details ".$row['somefield'].$row['someotherfield'];
}

?>

 

Change $row['somefield'] to a field you want to display, etc.

 

All the best

 

Keith

This is what I have so far:

 

$q = "SELECT * FROM my_states LEFT OUTER JOIN my_stores ON my_states.state_id = my_stores.state_id ORDER BY my_states.state_id";
$r = mysql_query($q) or die(mysql_error());

$prevState = "";

while ($row = mysql_fetch_array($r)){

	$state = $row['state'];
	$state_id = $row['state_id'];
	$store = $row['store'];

	if($prevState != $state){
		$prevState != $state;
		print $state . '<br />';
	}

	echo $store . '<br /><br />';
}

 

At the moment, I'm getting each location printed under their respected states, but with each state always being printed above each location.

 

I'm stuck on how to print the State name once, above all the locations..

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.