mrbubbles
mrbubbles

Reputation: 697

Using $wpdb object in Wordpress functions.php file

I have an issue with not being able to call the get_results() function on the $wpdb object inside the Wordpress functions.php file.

Exact error: Call to a member function get_results() on a non-object in [...]

This is my function;

global $wpdb;
function query_students($year){
   $wpdb->get_results(
      $wpdb->prepare(
         "SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key ='foobar' AND meta_value = '{$year}'"
      )
   );
$wpdb->flush();
}

As you can see I've globalised the $wpdb variable, and this function works great in the page template file. I would just prefer it if my functions weren't dotted around the place, and in some kind of centralised file.

Thanks in anticipation! :)

Upvotes: 1

Views: 6303

Answers (2)

Focus iTech Solutions
Focus iTech Solutions

Reputation: 21

I was running following query in functions.php

SELECT
    `id`,
    `user`,
    `width`,
    `type`,
    `source`,
    `link`,
    `expire`,
    `impressions`,
    `clicks`
FROM adds
WHERE `width` = 728 and `impressions` < (
    SELECT MAX(`impressions`)
    FROM adds
    WHERE `width` = 728
) OR `width`=728 and `clicks` < (
    SELECT MAX(`clicks`)
    FROM adds WHERE `width`=728
) ORDER BY RAND() LIMIT 3

it was not working but after adding the line global $wpdb in the begining of the function helped me and query is running fine. Thanks

Upvotes: 0

maiorano84
maiorano84

Reputation: 11951

"Globalizing" a variable that's already in global scope does nothing. Case and point:

global $a; //does nothing
$a = 'foo';
global $a; //does nothing
foo();
echo $a; //'foo'
bar();
echo $a; //'bar'
function foo()
{
    $a = 'bar';
}
function bar()
{
    global $a;
    $a = 'bar';
}

The global keyword does not permanently make the defined variable global in scope. Think of it as a way to define a variable in a function and set its value to whatever a variable with the same name is outside of the function.

You need to move your global declaration INTO the function to make the $wpdb object in the Global scope available within the function's scope:

function query_students($year){
    global $wpdb;
    $wpdb->get_results(
    $wpdb->prepare(
     "SELECT * FROM {$wpdb->prefix}usermeta WHERE meta_key ='foobar' AND meta_value = '{$year}'"
    ));
    $wpdb->flush();
}

Upvotes: 3

Related Questions