3

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?

2 Answers 2

3
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) 
       );
    }
}
0
2

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');
    }

}
1
  • thanks a lot I will keep in mind, I would vote up but not enough reputation
    – fefe
    Nov 25, 2012 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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