How to query database (4 posts)

  1. preitybansal
    Posted 3 years ago #


    I have created custom tables in WP database and now want to retrieve the data and display them in the required fields. Like I have one table named flipcountries which have a number of countries name and they are to be displayed in a drop-down field so that user can select one of them.

    I have read about wpdb class and all the references but still not able to display the content.

    Please help how to loop the results..Code I used is:

    global $wpdb;
    $countries = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb
    foreach ($countries as $country) {
    echo "<option value=country>country</option>";								}

    here country is the second column in flipcountries table.
    I am not sure what should be the code inside foreach loop..

    Any help will be appreciated.

    Thank you

  2. Chris
    Posted 3 years ago #

    If the column you want to retrieve from your custom table would be called "country" it should work like this:

    $countries = $wpdb->get_results( 'SELECT country FROM ' . $wpdb->prefix . 'flipcountries', OBJECT_K );
    foreach( $countries as $country ) {
      echo '<option value="' . $country->country . '">' . $country->country . "</option>\n";
  3. preitybansal
    Posted 3 years ago #

    Hi Chris

    Thanks a lot.. it worked..

    You were so helpful.. Really appreciate that.

  4. Chris
    Posted 3 years ago #

    You're welcome. Glad it worked out :)

Topic Closed

This topic has been closed to new replies.

About this Topic