Support » Plugins » $wpdb->get_var – won’t query db

  • Resolved elucidblue


    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?

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

    (@otto42) Admin

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

    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)

    Moderator Samuel Wood (Otto)

    (@otto42) Admin

    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:

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘$wpdb->get_var – won’t query db’ is closed to new replies.