queries inside of a class

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?

Related posts

Leave a Reply

2 comments

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