728x90

I'm writing a plugin and trying to request some data from a custom table in my database using:

$current_text = $wpdb->get_results("SELECT text FROM addtext ORDER BY id DESC LIMIT 1");

but just get the error Undefined variable: wpdb

Any idea why this isn't working? I've followed the docs and scoured Google, with no luck. Still pretty new to WP plugins so probably something obvious.

Thanks!

I needed to use global $wpdb; in my function.

    One note to add: You cannot use global inside a class, and of course you have to use global in order to get your objects to work using $wpdb.

    While you can't use global immediately inside a class, you must declare $wpdb as global inside a function inside the class, and this does work.

    e.g. This gives you an error:

    class wpdb_test {
            global $wpdb; // can't use global as a direct 'child' of a class
            public function __construct () {
                ...
            }
    }

    Because global can't be used directly inside a class. Likewise, simply referencing $wpdb inside the class also gives you an error because the object doesn't know what $wpdb is. You have to declare $wpdb as global from inside a function that is inside your class.

    e.g. This works just fine:

    class wpdb_test {
            public $variable_name;
            public function __construct () {
                global $wpdb; // safe to use because it's inside a function
                ...
            }
    }

    ...and because $wpdb has been declared global inside a function inside a class you are able to use it.


    + Recent posts