Support » Plugins » Using $wpdb-> to access a custom table

Viewing 7 replies - 1 through 7 (of 7 total)
  • Moderator Samuel Wood (Otto)

    (@otto42) Admin

    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.

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

    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)

    This will work:

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

    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 🙂

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

    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

Viewing 7 replies - 1 through 7 (of 7 total)
  • The topic ‘Using $wpdb-> to access a custom table’ is closed to new replies.