David
David

Reputation: 1191

Join two MySQL tables and group result with php

I have the following code to populate cities in a table.

$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);


echo "<table>";
while ($row = mysql_fetch_assoc($cities_result))
{
    echo "<tr>";
    echo "<td>".$row['city_name'] . "</td>";
    echo "</tr>";
}
echo "</table>";

Now I need to group every city by a region so I created the table called city_region_selection and added a Foreign key from the new column "region_id" in the city_selection table to region_id in the new table.

I'm now struggling to present this data in a nice html table using PHP.

Is it even possible to populate first a table row with region_name and then some subrows containing cities from that region? Please see this image for details:

http://oi48.tinypic.com/2uq0z9x.jpg

Upvotes: 2

Views: 319

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191749

You just have to do a little preprocessing:

/* SQL
   SELECT
      city_name,
      region_name
   FROM
      city_selection
      NATURAL JOIN city_region_selection
SQL */

$regions = array();
while ($result->fetch()) {
   if (!isset($regions[$result->region_name])) {
      $regions[$result->region_name] = array();
   }
   $regions[$result->region_name][] = $result->city_name;
}

Alternate Method with SQL focus

/* SQL
   SELECT
      region_name,
      GROUP_CONCAT(city_name SEPARATOR ',') cities
   FROM
      city_selection
      NATURAL JOIN city_region_selection
   GROUP BY
      region_name
*/

$regions = array();
while ($result->fetch()) {
   $regions[$result->region_name] = explode(',', $result->city_name);
}

Help

Note that the while syntax is just abridged. You would probably replace it with

while ($row = mysql_fetch_assoc($cities_result)) {
   $regions[$row['region_name']] = explode(',', $row['city_name']);
}

... for example

Once regions is built, simply do this:

foreach ($regions as $region => $cities) {
   echo "<tr><td>$region</td></tr>";
   foreach ($cities as $city) {
      echo "<tr><td class="tabbed">$city</td></tr>";
   }
}

Upvotes: 2

Related Questions