首页 > 解决方案 > 如何在课堂上使用 $wpdb

问题描述

你能帮我使用$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);
        }
    }
}

标签: wordpress

解决方案


尝试这个:

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

推荐阅读