Codeigniter – Save config data in database

In this post, I would like to show you saving config data in the database in your CodeIgniter application. And I will show you, How you can get these data when you need to use in your project.

Codeigniter – Save config data in database

To achieve this you are going to use CodeIgniter hooks. To initialize the hooks class one must have to enable it as shown below –

Open application/config/config.php file and set enable_hooks config value to true.

Steps to Save Codeigniter config data in database

There are several hook points available in CodeIgniter. As for current requirement you need use “post_controller_constructor” hook point. let’s open application/config/hooks.php file and add following code. as you enabled hooks with above config option, hooks.php file will be auto-loaded by CI.

Code Explained

post_controller_constructor – Called immediately after your controller is instantiated, but prior to any method calls happening.

$CI = &get_instance(); – This will return “reference of the CI superobject”.

$CI->AppConfigModel->get_configurations() – From the CI superobject, accessing auto-loaded modal “AppConfigModel” and reading get_configurations() method. This method will read database and return all the available config data.

After that, iterating over the data and by using CI superobject accessing set_item() method via config object and setting key and value of the config data.

Here is the auto loaded Config options – For application/config/autoload.php file

Here is the table schema –

Here is AppConfigModel Model – application/models/AppConfigModel.php

That is it, now you can access config data from anywhere in the system by using this script config->item('sitename'); ?>.

I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.

Arjun
I am Arjun from Hyderabad (India). I have been working as a software engineer from last 7+ years, and its my passion to learn new things and implement them as a practice. Aside from work, I likes gardening and spending time with pets.
DMCA.com Protection Status