WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Cannot Run Query on Newly-Created Table in WordPress (5 posts)

  1. johnwinlwin
    Member
    Posted 3 years ago #

    Hi,

    I can run the following query on 'wp_links' tables or any other built-in tables in WordPress/MySQL database.
    <?php
    global $wpdb;
    $comment_count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $wpdb->links;"));
    echo "<p>Total comments: " . $comment_count . "</p>";
    ?>

    PROBLEM is that after I added new table, say 'wp_newtable', and I tried to run the same query on 'wp_newtable', nothing is shown although I have put some records in wp_newtable.

    Did i miss something? Do I need to update some setting??

    Appreciate your help!

  2. vtxyzzy
    Member
    Posted 3 years ago #

    If you are using $wpdb->newtable for the table name in your query, you will not get any results because $wpdb does not have a record of your new table. You must add the table to $wpdb before you use it in queries - typically in functions.php:

    <?php function my_theme_init() {
        global $wpdb;
        $wpdb->newtable = $wpdb->prefix . 'newtable';
    }
    add_action('init','my_theme_init');
  3. johnwinlwin
    Member
    Posted 3 years ago #

    Hi xtxyzzy, thanks for your help.

    I found the functions.php in /wp-content/themes/ folder.

    When I open the functions.php, I found the following code:

    <?php
    define("THEME_FUNCTIONS",TEMPLATEPATH."/functions/");
    define("THEME_INCLUDES",TEMPLATEPATH."/includes/");
    define("THEME_CACHE",TEMPLATEPATH."/cache/");
    
    require_once(THEME_FUNCTIONS."init.php");
    require_once(THEME_INCLUDES."widgets/init.php");
    require_once(THEME_INCLUDES."shortcodes/init.php");
    require_once(THEME_INCLUDES."theme_config.php");
    
    ?>

    Can I just put your code below the above code? Thanks you again for your help. :-)

  4. johnwinlwin
    Member
    Posted 3 years ago #

    Hey xtxyzzy,

    I got it. Thanks again for your code. It works.

    But I'm wondering what if I create 2 new tables and those 2 tables have one-to-many relationship. Do I need to declare or specify this relationship in the WordPress?

  5. vtxyzzy
    Member
    Posted 3 years ago #

    The relationship is expressed in the SQL of the query, so WP does not need it elsewhere.

Topic Closed

This topic has been closed to new replies.

About this Topic