Welcome Guest, Not a member yet? Register   Sign In
Storing variables in database
#1

[eluser]Unknown[/eluser]
I needed config variables, which I could change in my app. And since CodeIgniter doesn’t allow to do that, I made simple library that allows storing variables in database. (for php5 only)

Code:
CREATE TABLE IF NOT EXISTS `config` (
  `key` varchar(255) NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY  (`key`)
)

Code:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Dbvars Library
* Simplifies storing variables in database, for example configuration variables.
*
* You must create table first.
**/
/*

CREATE TABLE IF NOT EXISTS `config` (
  `key` varchar(255) NOT NULL,
  `value` text NOT NULL,
  PRIMARY KEY  (`key`)
)

*/
/**
* Use:
*     $this->load->database();
*     $this->load->library('dbvars');
*    
* To set value: $this->dbvars->key = 'value';
* To get value:    $this->dbvars->key
* To check if the variable isset: $this->dbvars->__isset($key);
* To unset variable use: $this->dbvars->__unset($key);
* As of PHP 5.1.0 You can use isset($this->dbvars->key), unset($this->dbvars->key);
*
* @version: 0.1 (c) _andrew 27-03-2008
**/
class Dbvars {
    const TABLE = 'config';
    //Table where variables will be stored.
    
    private $data;
    private $ci;
    
    function __construct()
    {
        $this->ci = &get;_instance();
    
        $q = $this->ci->db->get(self::TABLE);
        foreach ($q->result() as $row)
           {
               $this->data[$row->key] = unserialize($row->value);
           }
           $q->free_result();
    }

    function __get($key){
        return $this->data[$key];
    }
    
    function __set($key, $value){
        if (isset($this->data[$key])){
            $this->ci->db->where('key', $key);
            $this->ci->db->update(self::TABLE, array('value' => serialize($value)));
        } else {
            $this->ci->db->insert(self::TABLE, array('key' => $key, 'value' => serialize($value)));
        }
        $this->data[$key] = $value;
    }
        
    /**  As of PHP 5.1.0  */
    function __isset($key) {
        return isset($this->data[$key]);
    }

    /**  As of PHP 5.1.0  */
    function __unset($key) {
        $this->ci->db->delete(self::TABLE, array('key' => $key));    
        unset($this->data[$key]);
    }    
}
?>




Theme © iAndrew 2016 - Forum software by © MyBB