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

[eluser]EEssam[/eluser]
Hello,

I have the following code in my old app to get settings from DB:

// get global settings
$result = mysql_query("SELECT varname, value FROM setting");

if (!$result)
{
die ('Could not successfully get settings from DB: ' . mysql_error());
}

$options = array();

while ($row = mysql_fetch_assoc($result))
{
$options[$row['varname']] = $row['value'];
}

mysql_free_result($result);

What would be the ideal method to integrate it with CI?

Please advise.
#2

[eluser]Pascal Kriete[/eluser]
Code:
$this->db->select('varname, value');
$query = $this->db->get('setting');

if ($query->num_rows() == 0)
{
    show_error('Could not get settings from DB');
}

$options = array();

foreach($query->result() as $row)
{
    $options[$row->varname] = $row->value;
}
#3

[eluser]EEssam[/eluser]
Thanks but I want to make the settings globally available. Where I should store the code is this case?
#4

[eluser]Pascal Kriete[/eluser]
Code:
class Settings {
    
    var $CI;
    var $options;
    
    /**
     *Constructor
     *
     * @access    public
     */
    function Settings()
    {
        $this->CI =& get_instance();
        $this->options = array();

        // Load database class
        $this->CI->load->database();

        // Get global variables
        $this->_init();
    }

    // ------------------------------------------------------------------------    
    
    /**
     * Set settings
     *
     * @access    private
     */
    function _init()
    {        
        $this->CI->db->select('varname, value');
        $query = $this->CI->db->get('setting');

        if ($query->num_rows() == 0)
        {
            show_error('Could not get settings from DB');
        }

        foreach($query->result() as $row)
        {
            $this->options[$row->varname] = $row->value;
        }
    }
}

Put that in a library and autoload it. Now all your settings should be available through $this->settings->options['whatever'].
#5

[eluser]EEssam[/eluser]
Hi inparo,

It worked like a charm. Can you please just tell me why I should place this in a library and not in a helper or a plugin?
#6

[eluser]EEssam[/eluser]
Or even in a model and set it to autoload... it makes more since to me (since models are associated with data)
#7

[eluser]Pascal Kriete[/eluser]
No real reason, in the spur of the moment a library is what I had on hand. A model would probably be the better choice when you consider the MVC paradigm.




Theme © iAndrew 2016 - Forum software by © MyBB