Easy options table class

<?php

/*
* HypOptionsTable Class
* Constructor: $new_hyper_options = new HypOptionsTable($table_name,$option_names);// Pass options names as an array
* Access the table: $hyper_options_ref = new HypOptionsTable($tablename);// No second argument = no table created
*
* For MU it is usefull to create a table with the prefix of the child blog, like wp_3_mytablename. These will be cleaned
* up when said child site is deleted from the MU interface.
*/

class HypOptionsTable{
private $_table_name;
private $_option_names;

public function __construct($table_name,$option_names = false){
if($table_name) $this->_table_name = $table_name;
if($option_names){
$this->_option_names = $option_names;
$this->create_table();
}
}
private function create_table(){
global $wpdb;
$table_name = $this->_table_name;
$option_names = $this->_option_names;
$db_version = '1.0';
if($wpdb->get_var("show tables like '$table_name'") != $table_name){
$sql = "CREATE TABLE " . $table_name . " (
id mediumint(9) NOT NULL AUTO_INCREMENT,
option_name VARCHAR(100) NOT NULL,
option_value TEXT NOT NULL,
UNIQUE KEY id (id)
);";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
add_option('db_version',$db_version);
//Instert Tables
foreach($option_names as $name){
$wpdb->insert($table_name, array('option_name' => $name,'option_value' => ''));
}
}
}
public function addOption($option_name,$option_value){
global $wpdb;
$table_name = $this->_table_name;
if($wpdb->query("SELECT * FROM $table_name WHERE option_name = '$option_name'")) $this->updateOption($option_name,$option_value);
else $wpdb->insert($table_name, array('option_name' => $option_name,'option_value' => $option_value));
}
public function updateOption($option_name,$option_value){
global $wpdb;
$table_name = $this->_table_name;
$wpdb->update($table_name, array('option_value' => $option_value), array('option_name' => $option_name));
}
public function getOption($option_name){
global $wpdb;
$table_name = $this->_table_name;
$results = $wpdb->get_row("SELECT option_value FROM $table_name WHERE option_name = '$option_name'");
return $results->option_value;
}
public function deleteOption($option_name){
global $wpdb;
$table_name = $this->_table_name;
$wpdb->query("DELETE FROM $table_name WHERE option_name = '$option_name'");
}

}//End HypOptionsTable

/*
//Test Constructor, creates table
$option_name_array = array('username','email','password');
$new_hyper_options = new HypOptionsTable('wp_hyper_options',$option_name_array);

//Test Reference - New table not created due to lack of second argument
$hyper_options = new HypOptionsTable('wp_hyper_options');
$hyper_options->addOption('rudeness_level','wicked bad');

//Test Update
$hyper_options->updateOption('username','dippy');

//Test Get
echo $hyper_options->getOption('username');
*/

?>

0 Comments

You must be logged in to post a comment.