Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm building a plugin and I'm quite new to wordpress I have a class what has couple of methods what should execute database queries. The class look as it follows

class MyClass{

        private $wpdb;

        function __construct(){
            global $wpdb;

        }

        function query(){
        $wpdb->query( $wpdb->prepare("INSERT INTO $wpdb->wp_competitors

                        ( id, field_key, field_value ) VALUES ( %d, %s, %s )",1,

                        $field_key, $field_value) );

        }

     }

I would like to be able to use inside of my class wordpress native database class, how to do this?

share|improve this question

2 Answers 2

up vote 1 down vote accepted
class MyClass{
    function __construct(){
        global $wpdb;
        $this->db = $wpdb;
    }

    function query(){
       return $this->db->query( 
            $this->db->prepare("INSERT INTO {$this->db->wp_competitors} (id, ield_key, field_value) VALUES ( %d, %s, %s )",
            1, $field_key, $field_value) 
       );
    }
}
share|improve this answer
    
thanks a lot accepted –  fefe Nov 25 '12 at 10:48

A disadvantage of using a custom $db property in your class is that you won't be able to use it in static methods, if you ever were to create some. Two alternative approaches:

class MyClass {

    public function query1() {
        global $wpdb;
        $wpdb->query('SQL');
    }

    public function query2() {
        $GLOBALS['wpdb']->query('SQL');
    }

}
share|improve this answer
    
thanks a lot I will keep in mind, I would vote up but not enough reputation –  fefe Nov 25 '12 at 11:13

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.