Jump to content

Recommended Posts

I am trying to combine two different queries but I can only seem to get the first query to display. It only comes up with the first state. Here is my code.

 

$sql = "SELECT DISTINCT state from cities where country = 'US' ORDER BY state";
        $result = mysql_query ($sql);

            while($row = mysql_fetch_array ($result, MYSQL_ASSOC))
        {
$state = $row[state];
$arr = array($state);
reset($arr);
while (list(, $value) = each($arr)) {

}
}
foreach ($arr as $key => $value) {
$sql = "SELECT cities from cities where country='US' AND state='$value'";
        $result = mysql_query ($sql);

            while($row = mysql_fetch_array ($result, MYSQL_ASSOC))
        {
$cities = $row[cities];
}
}

Link to comment
https://forums.phpfreaks.com/topic/87082-merging-two-different-queries-together/
Share on other sites

I think what you are looking for is something like this:

 

$sql = "SELECT DISTINCT state from cities where country = 'US' ORDER BY state";
$result = mysql_query($sql);

$states = array();
while($row = mysql_fetch_array ($result, MYSQL_ASSOC)){
  $states[] = $row[state];
}

$cities = array();
foreach ($states as $value) {
  $sql = "SELECT cities from cities where country='US' AND state='$value'";
  $result = mysql_query ($sql);
  while($row = mysql_fetch_array ($result, MYSQL_ASSOC)){
    $cities[] = $row[cities];
  }
}

 

It would help if you specified exactly what you are trying to accomplish.

I would like to display each city in the database from every state in the US.

 

table 1 "state - CA, cities - Los Angeles, San Jose, San Francisco"

table 2 "state - WA, cities - Olympia, Seattle, Tacoma"

 

 

Displayed as:

 

Los Angeles

Olympia

San Jose

San Francisco

Seattle

Tacoma

 

It seems like a nested loop would be better:

 

$s_sql = "SELECT `state` FROM `cities` WHERE `country` = 'US' ORDER BY `state`";
$s_result = mysql_query($s_sql);
while($state = mysql_fetch_assoc($result)){
  echo "Current state: {$state['state']}\n";
  $c_sql = "SELECT cities from cities where country='US' AND state='$value'";
  $c_result = mysql_query ($c_sql);
  while($city = mysql_fetch_assoc($c_result)){
    echo " -{$city['cities']\n";
  }
}

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.