how to wordpress loop for each with database query

So I’m trying to custom code a loop using for_each in WordPress so that it displays a code (city) for each table that has a state name.. my outcome would be like this displayed;

- New York
  -- city1
  -- city2
  -- city3
- New Jersey
  -- city1
  -- city2

and so on.. in the database (mysql) each entry is placed into a row with table for State and Table for City but in same row…

Read More

I’ve tried doing the following but I’m failing in it;

$states = $wpdb->get_row("SELECT * FROM $wpdb->wp_em_locations WHERE location_state=*);
$city = $wpdb->get_row("SELECT * FROM $wpdb->wp_em_locations WHERE location_town=*);
foreach ( $states as $state ) {
echo '$state';
echo '$city';
}

Related posts

Leave a Reply

1 comment

  1. Edited: get_row may not be the best method of gaining this infomration. I am using your context to get this information but this may be the method you are looking for.

    $states = $wpdb->get_results("SELECT location_state FROM wp_em_locations GROUP BY location_state");
    foreach ( $states as $state ) {
      echo $state->location_state;
      $cities = $wpdb->get_results("SELECT location_town FROM wp_em_locations WHERE location_state = '" . $state . "'");
      foreach ($cities as $city) {
          echo $city->location_town;
      }
    }
    

    Reference: https://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results