WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] Using $wpdb-> to access a custom table (8 posts)

  1. Ian Dunn
    Member
    Posted 8 years ago #

    I created my own custom table using the method described in (http://codex.wordpress.org/Creating_Tables_with_Plugins). I've tried accessing it using the normal method ($wpdb->tablename) but it doesn't work and I have to use $tableprefix instead.

    Is there a way to be able to just use the normal $wpdb->tablename method instead of having to use $tableprefix?

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 8 years ago #

    I think you misunderstand what $wpdb->tablename is actually doing.

    $wpdb is an instance of the wpdb class, which is defined in wp-includes/wp-db.php. Those "table names" are actually variables defined inside the class.

    So unless you modify the wpdb class itself to have a new variable which you populate, no, you can't use your table name there.

  3. Lester Chan
    Member
    Posted 8 years ago #

    If you are using a plugin, put it inside the plugin
    $wpdb->custom_table_name = $tableprefix.'custom_table_name';

  4. Ian Dunn
    Member
    Posted 8 years ago #

    Gamerz, that didn't work. I haven't done anything w/ PHP classes, but if they're like C++ then I wouldn't be able to add a private variable from outside the class anyway. Or am I just doing it wrong? I tried putting that (it's actually $table_prefix, not $tableprefix) inside the function that's called when the plugin activates, and also just inside the page where I'm quering the DB, but it doesn't work, the query just comes out being

    "INSERT INTO VALUES()..." (the table name doesn't show up)

  5. pizdin_dim
    Member
    Posted 8 years ago #

    This will work:

    if (!isset($wpdb->tablename)) {
    $wpdb->tablename = $table_prefix . 'tablename';
    }

  6. Ian Dunn
    Member
    Posted 8 years ago #

    Huh, it worked that time, but what pizdin_dim suggested was the same as GamerZ, so I must have been doing something wrong the first time.

    Thanks guys :)

  7. Lester Chan
    Member
    Posted 8 years ago #

    no problem, just a gentle reminder, you need to global $wpdb in the function

  8. forceagainstsomething
    Member
    Posted 8 years ago #

    Yeah, I do this for most of my plugins that require their own table. At the top of the plugin, just doing this:

    $wpdb->myplugintable = $table_prefix . 'myplugintable';

    Works just fine.

    - Sean
    http://www.headzoo.com

Topic Closed

This topic has been closed to new replies.

About this Topic