我知道这是一个很老的问题,但也许有人会觉得它有用。处理新数据库、表版本上的函数并在不存在时创建的小计算器。
class ACCESS_TBDB {
private $wpdb = null;
private $accessTable = \'table_prefix\'; // just name of your table prefix
private $accessTableVer = \'1.0.7\'; // table version
private $accessTableOptName = \'access_db_ver\'; // name for option for db version
public function __construct()
{
global $wpdb;
//I does not like to call global $wpdb in every function in the class
$this->wpdb = $wpdb;
$tablename = $this->accessTable;
//set our table prefix
$this->wpdb->access_table = $this->wpdb->prefix . $tablename;
// every time check if db need to be created or not
$this->checkAccessDatabase();
}
private function createDBSQL(){
// create db sql for table
$charset = $this->wpdb->get_charset_collate();
$sql = "
CREATE TABLE {$this->wpdb->access_table} (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
name TINYTEXT,
type VARCHAR(10),
value SMALLINT DEFAULT 0 NOT NULL,
created_at DATETIME DEFAULT NULL,
PRIMARY KEY (id)
) $charset;
";
return $sql;
}
private function checkAccessDatabase(){
$version = $this->accessTableVer;
//handle DB versions
$db_version = get_option( $this->accessTableOptName , \'0.0.0\');
//Without we will face error on dbDelta and maybe_create_table
require_once(ABSPATH . \'wp-admin/includes/upgrade.php\');
$dbCreateSql = $this->createDBSQL();
// check if maybe DB need upgrade
if (version_compare($version, $db_version, \'>\')) {
// if it contain old dev/legacy versions
if (version_compare($db_version, \'1.0.0\', \'<\')) {
$this->wpdb->query("DROP TABLE IF EXISTS {$this->wpdb->access_table};");
}
dbDelta($dbCreateSql);
update_option( $this->accessTableOptName , $version);
}else{
//https://developer.wordpress.org/reference/functions/maybe_create_table/
// just check DB if exist in case it was deleted because of reasons ... :)
$recreate = maybe_create_table( $this->wpdb->access_table, $dbCreateSql );
if(!$recreate){
update_option( $this->accessTableOptName , $version);
}
}
}
... other functions ...
}