如何在课程中使用$ wpdb

时间:2019-11-25 11:14:10

标签: wordpress

您能帮我使用$ wpdb吗?在上课吗?错误标记在注释中(2种情况)。

class Installer {

    public function __construct($a) {
        global $wpdb; // Expecting stateent
        private $table_name = $this->$wpdb->prefix . "ved_currencies";
        private $charset_collate = $wpdb->get_charset_collate();
    }


    public function activate(){
        if ($wpdb->get_var("SHOW TABLES LIKE '{$this->table_name}'") != $this->table_name) { // Undefined variable $wpdb

            $sql = "CREATE TABLE $this->table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT UNIQUE,    
            date date not null,
            char_code varchar(3) NOT NULL,
            name varchar(40) NOT NULL,
            nominal int(9) NOT NULL,
            value DECIMAL(20,20) NOT NULL,
            PRIMARY KEY  (date, char_code)
            )    $this->charset_collate;";
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

尝试一下:

class Installer {

    public function __construct($a) {
        global $wpdb; // Expecting stateent
        private $wpdb = $wpdb; // edit
        private $table_name = $this->$wpdb->prefix . "ved_currencies";
        private $charset_collate = $wpdb->get_charset_collate();
    }


    public function activate(){
        if ($this->wpdb->get_var("SHOW TABLES LIKE '{$this->table_name}'") != $this->table_name) { // edit

            $sql = "CREATE TABLE $this->table_name (
            id mediumint(9) NOT NULL AUTO_INCREMENT UNIQUE,    
            date date not null,
            char_code varchar(3) NOT NULL,
            name varchar(40) NOT NULL,
            nominal int(9) NOT NULL,
            value DECIMAL(20,20) NOT NULL,
            PRIMARY KEY  (date, char_code)
            )    $this->charset_collate;";
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
            dbDelta($sql);
        }
    }
}

答案 1 :(得分:0)

您没有在课程属性中设置$wpdb。看__construct()

并使用maybe_create_table代替dbDelta。

class Installer {

    private $wpdb;
    private $table_name;
    private $charset_collate;

    public function __construct( $a ) {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table_name = $this->$wpdb->prefix . 'ved_currencies';
        $this->charset_collate = $wpdb->get_charset_collate();
    }


    public function activate(){
        $sql = "CREATE TABLE $this->table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT UNIQUE,    
        date date not null,
        char_code varchar(3) NOT NULL,
        name varchar(40) NOT NULL,
        nominal int(9) NOT NULL,
        value DECIMAL(20,20) NOT NULL,
        PRIMARY KEY  (date, char_code)
        )    $this->charset_collate;";
        if ( ! function_exists( 'maybe_create_table' ) ) {
            require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        }
        maybe_create_table( $this->table_name, $sql);
    }
}