Pages

Save Codeigniter config data in MySql database

Friday, January 27, 2012
In this tutorial, I want to show you how to save the codeigniter config data in mysql database. It means we will save config data in mysql and can grab these data when we need to use in our project and can also edit form our site dynamically.

Step 1: Configuration

For application/config/routes.php file

$route['default_controller'] = "home";

For application/config/config.php file

$config['base_url'] = 'http://localhost/ci_config/';

and

$config['enable_hooks'] = TRUE;

For application/config/autoload.php file

$autoload['libraries'] = array('database');
and
$autoload['helper'] = array('url','form');
and
$autoload['model'] = array('Siteconfig');

For application/config/database.php file

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'ciconfig';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';

For application/config/hooks.php file

You need to add below code to your hooks.php file.
$hook['post_controller_constructor'] = array(
         'class'    => '',
         'function' => 'load_config',
         'filename' => 'my_config.php',
         'filepath' => 'hooks'
         );
You can learn more about hooks in the CI documentation here.

Setp 2: Creating Hooks file

Open new document in your favourite editor and type below code and save as application/hooks/my_config.php

<?php
  //Loads configuration from database into global CI config
  function load_config()
  {
   $CI =& get_instance();
   foreach($CI->Siteconfig->get_all()->result() as $site_config)
   {
    $CI->config->set_item($site_config->key,$site_config->value);
   }
  }
?>

We grab the config data from our database by using Siteconfig model. And set the data to global CI config. So we need to create Siteconfig model in our model folder.

Step 3:Creating database

Create a database from your MySql admin as ciconfig and run below code in your mysql tool.

CREATE TABLE IF NOT EXISTS `config_data` (
  `key` varchar(255) NOT NULL,
  `value` varchar(255) NOT NULL,
  PRIMARY KEY (`key`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `config_data`
--

INSERT INTO `config_data` (`key`, `value`) VALUES
('sitedescription', 'Tutorials for Web development and design'),
('sitename', 'TutsforWeb');

Step 4:Creating Siteconfig model

Open new document in your favourite editor and type below code and save as application/models/siteconfig.php

<?php
class Siteconfig extends CI_Model {

 public function __construct()
 {
  parent::__construct();
 }
 public function get_all()
 {
  return $this->db->get('config_data');
 }
 public function update_config($data)
 {
  $success = true;
  foreach($data as $key=>$value)
  {
   if(!$this->save($key,$value))
   {
    $success=false;
    break;  
   }
  }
  return $success;
 }
 public function save($key,$value)
 {
  $config_data=array(
    'key'=>$key,
    'value'=>$value
    );
  $this->db->where('key', $key);
  return $this->db->update('config_data',$config_data); 
 }
}

get_all() function is used in our my_config hooks file to grab all data from our database.
update_config() function is used to update our config data when the form is submitted from config view file.
save() function is called form the update_config() function to update one by one.

Step 5:Creating home Controller

Open new document in your favourite editor and type below code and save as application/controllers/home.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
  public function index()
  {
   $this->load->view('home');
  }
  public function config()
  {
   $this->load->view('config');
  }
  public function update()
  {
   $update_data=array(
      'sitename'=>$this->input->post('sitename'),
      'sitedescription'=>$this->input->post('sitedescription')
      );
   $success = $this->Siteconfig->update_config($update_data);
   if($success) redirect("/home/index");
  }
}
?>

Step 6:Creating view files

Open new document in your favourite editor and type below code and save as application/views/home.php

<!DOCTYPE html>
<html>
  <head>
   <title><?php echo $this->config->item('sitename'); ?></title>
  </head>
<body>
  <h1><?php echo $this->config->item('sitename'); ?></h1>
  <h4><?php echo $this->config->item('sitedescription'); ?></h4>
  <a href="<?php echo base_url(); ?>index.php/home/config">Site Config</a>
</body>
</html>
As you see above code, we can use our config data by using this script <?php echo $this->config->item('sitename'); ?>

Below is the screenshot of our site.


We need to create the config view file to edit config data dynamically. Open new document in your favourite editor and type below code and save as application/views/config.php
<!DOCTYPE html>
<html>
  <head>
   <title><?php echo $this->config->item('sitename'); ?></title>
  </head>
<body>
  <h1><?php echo $this->config->item('sitename'); ?></h1>
  <h4><?php echo $this->config->item('sitedescription'); ?></h4>
  <div id="content">
  <?php echo form_open("home/update"); ?>
  <p>
   <label for="sitename">Site Name :</label>
   <input type="text" name="sitename" id="sitename" value="<?php echo $this->config->item('sitename'); ?>" size="40" />
  </p>
  <p>
   <label for="sitedescription">Site Description :</label>
   <input type="text" name="sitedescription" id="sitedescription" value="<?php echo $this->config->item('sitedescription'); ?>" size="40" /> 
  </p>
  <p>
   <input type="submit" value="Submit" />
  </p>
  <?php echo form_close(); ?>
</div>
</body>
</html>
If you click the Site Config from our home page, this page will be loaded and you can edit and update our config data.


Below is the screenshot of config view file.

Read more ...