• Resolved aaronsho

    (@aaronsho)


    This is a hypothetical trivial example just to make things easier. It’s exactly what I’m trying to do, but in very simple terms.

    I created a table called ‘animals’ in the wordpress database. it has a list of animal names.

    To begin with, how do I query the list of names from the table?

    I created a function in functions.php called “mysite_list_animals”.

    It simply has:

    <?php
    function mysite_list_animals() {
    include_once(‘wp-config.php’);
    include_once(‘wp-load.php’);
    include_once(‘wp-includes/wp-db.php’);
    $myrows = $wpdb->get_results( “SELECT name FROM animals” );
    }
    ?>

    I want to call this function from a page so in page.php I entered:

    <?php mysite_list_animals(); ?>

    I searched through two books, the codex and other online material but couldn’t figure out why it doesn’t work.

    Here are some basic questions I couldn’t find answers to:

    1) does the “$wpdb->get_results” function automatically print out the results? Or, do I have to iterate through the array?

    2) is the functions the correct place to put this, or should it be a plugin? (I imagine this is discretionary).

    Any other help to get this dang thing to work would be appreciated.

    thanks.

Viewing 3 replies - 1 through 3 (of 3 total)
  • If you’re calling this from a WP file, there’s no need for the includes, you only need such things in a non-wordpress file.

    If the animals table is in the WordPress database then the above should be fine, and you’ll get an array of objects back..

    If you want to see what’s in the result(the variable), you can use something like this(just for visibility of the data).

    print '<pre>';print_r( $myrows );print '</pre>';

    The pre tags just format(displays) the data in an easy to read format(incase you were wondering).

    Thread Starter aaronsho

    (@aaronsho)

    Thank you! Having someone confirm I’m on the right track really helps. The code to print out the array was also helpful.

    The only other thing I had to fix was to declare $wpdb as a global variable in my function using:

    global $wpdb

    Thanks again!

    Of course yes you would need to globalise the var(i missed that), else it’s outside the scope of the function..

    Happy to help and hear you’ve got things working how you want… ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘How does one use $wpdb to query custom tables?’ is closed to new replies.