WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] $wpdb->get_var - won't query db (4 posts)

  1. elucidblue
    Member
    Posted 7 years ago #

    I'm trying to use $wpdb to pull the name of a catogory by it's ID, but it stops the php page generation every time. (ie. the source code ends there, in the middle of the page)

    My line of code is: $name = $wpdb->get_var("SELECT cat_name FROM $wpdb->linkcategories WHERE cat_id=4");
    ...but it's failing on any call to get_var (for kicks and giggles I even copied the example straight out of the wpdb class reference page and got the same result.)

    I'm working in functions.php in my theme directory. I also had some confusion with the guy who runs the server about file permissions earlier. Is that a possibile cause, when everything else seems to work fine?

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

    Is this code inside a function? Did you forget to declare global $wpdb; at the beginning of your function?

  3. elucidblue
    Member
    Posted 7 years ago #

    Ah! That's it!

    What if I need to query the db from multiple different functions, do I only need to declare that in the first function that is called? If it's global, it shouldn't go out of scope, right?

    (I'm still fairly new to php)

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 7 years ago #

    No, it doesn't work that way in PHP. It's a bit backwards, sorta.

    A function gets its own, separate, scope. By declaring a variable as global inside the function, you are saying that you want to access that variable in the global scope instead.

    So for every function you use $wpdb in, you need to declare it global so that you can access the $wpdb in the global scope.

    This will help:
    http://www.php.net/variables.scope

Topic Closed

This topic has been closed to new replies.

About this Topic