Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Wednesday, 23 July 2014

How to enable a ReCaptcha for both HTTP / HTTPS (SSL enabled domain)

Please use the blow code to enable the Google ReCaptcha for HTTP & SSL enabled domain (i.e. HTTPS URL).
In fact, it will work for both types;
// Works only for HTTP - Get reCAPTCHA JS/HTML Code
$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

// Works for both HTTP / HTTPS - Get reCAPTCHA JS/HTML Code
$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'), null, true); // just added ", null, true" for ssl
The above code is snapshot of CodeIgniter (CI) based project.

Wednesday, 11 June 2014

POST request using REST API on CodeIgniter return Page Error 500

If you are trying to execute a POST request using REST API on CodeIgniter, and stoked with Page Error 500, or Request Page Not Found error,
An Error Was Encountered
The action you have requested is not allowed.
Then, please check for CSRF Protection check on application/config/config.php file > Line No below. 340 If you are already using the CSRF Security or already enabled, then add the following code just below 'csrf_expire' line.
/** Start of CSRF Skip for APIs Request
 *
 * If the REQUEST_URI has method is POST and requesting the API url,
 * then skip CSRF check, otherwise don't do.
 */
if (isset($_SERVER["REQUEST_URI"]) &&
   (isset($_SERVER['REQUEST_METHOD']) && ($_SERVER['REQUEST_METHOD'] == 'POST') ))
{
    if ( stripos($_SERVER["REQUEST_URI"], '/api/') === false )  
    {
        // If POST request is not for api request, Apply CSRF True
        $config['csrf_protection'] = TRUE;
    }
    else {
        // If POST request is for API, Skip CSRF Check
        $config['csrf_protection'] = FALSE;
    }
}
/** End of CSRF Skip for APIs Request */

Tuesday, 8 April 2014

"Filetype attempting to upload is not allowded" issue in CodeIgniter

If you are having issue on uploading the file in CodeIgniter, there is a bug with the File Upload Class in the _file_mime_type function ( or File Upload Class - MIME type detection issue).
Please check one of the following steps to fix the issue;

1. Uploading any image with the following config would generate the error ‘The filetype you are attempting to upload is not allowed.’:

$config = array(
 'upload_path' => './uploads/',
 'allowed_types' => 'gif|jpg|png'
);  
$this->load->library('upload', $config); 


2. Changing ‘allowed_types’ to ‘*’ allows the file to be uploaded, however the upload data array ( $this->upload->data() ) contains an error:
[file_type] => cannot open `' (No such file or directory)


3. Looking at system/libraries/Upload.php , Line 1058 tries to use an array value that does not exist.
@exec('file --brief --mime-type ' . escapeshellarg($file['tmp_path']), $output, $return_code); 

// Changed to: 

@exec('file --brief --mime-type ' . escapeshellarg($file['tmp_name']), $output, $return_code);  

Monday, 13 January 2014

Concatenation/Joining of two string using Smarty

// Concatenation / Join of two string using Smarty using '|cat:' keyword.
{$param_key = "param_"|cat:$item_name.id}

Wednesday, 30 October 2013

Codeigniter Pagination problem to locate the current page (if using CI default Library), AJAX Pagination Calls

If you are using default CI Pagination library then it would be chances of displaying the current page active although results status is displaying correctly.

In particular, when you are using config/routes.php to rewrite the URLs.

Well, if that case, you can resolve that issue by adding the uri_segment's value while initializing the pagination as below;

PS:  First find which segment of URI carries the page value, then add the segment value (not page value coz once you provide segment value then, it will use it to pull out the page value)
// Locate the uri_segment to locate the current page value.
$pagination['uri_segment'] = 3; 
Also, if you are wondering how to find the uri_segment value, then use below code to print all uri_segments array
$segments = $this->uri->segment_array();
print_r($segments);
Please find the sample pagination code as below;
$pagination = array();
$pagination['start']  = $start+1;
$pagination['limit']  = $limit;
$pagination['per_page'] = $limit;
$pagination['ipage']  = $ipage;
$pagination['total_rows'] = $this->m_yourmodel->function_result_count($where=array()); // only pull the approved ones.
$pagination['anchor_class'] = 'class="loadAjaxPage" '; // This class is added to make a AJAX Call if you want to load the pages via AJAX
$pagination['offset']  = ($start+$limit); // This is just for the View;

$pagination['uri_segment'] = 3; // Locate the uri_segment to locate the current page value.

$this->load->library('pagination');
$this->pagination->initialize($pagination);
a$pagination['page_links'] = $this->pagination->create_links();

To Load the Page from AJAX Call
Also I have added the loadAjaxPage class name on anchor_class pagination variable to load the page from AJAX calls.
// This class is added to make a AJAX Call if you want to load the pages via 
$pagination['anchor_class'] = 'class="loadAjaxPage" ';

Thursday, 22 August 2013

Reloading/Refreshing the image element(same filename) via Jquery AJAX

How to reload/refresh an element(image) in jQuery : Reloading/Refreshing the image element(same filename) via Jquery AJAX
$("#image1").attr("src", "{$base_url}tmp/survey/image1.png?ts=" + new Date().getTime());
$("#image2").attr("src", "{$base_url}tmp/survey/image2.png?ts=" + new Date().getTime());
Please check below the example of deployed function via AJAX...

function viewReportBtn(id) 
{  
 $('#survey_id').val(id);
 $('#dvLoading').show(); // Loader On
 
 var formData = $("#thisForm").serialize();
 
 $.ajax({ url: '{$base_url}school/reports/view',
  data: formData,
  type: 'post',
  complete: function(output) {
   var str = output.responseText;
   resultStatus = str.substr(0,7);
   resultText = str.substr(7,(str.length));
   
   if (resultStatus == 'success') {
    $('#searchResult').show().html(resultText); // show the result list on a search result container
    $("#lineChart").attr("src", "{$base_url}tmp/survey/linechart.png?ts=" + new Date().getTime());
    $("#pieChart").attr("src", "{$base_url}tmp/survey/piechart.png?ts=" + new Date().getTime());
   } else {
       $('#searchResult').html('').hide(); // hiding the search result container
   }
   $('#dvLoading').fadeOut(10); // To Switch Off the loader..
  }
 });
}

Monday, 29 July 2013

Create the N-level Categories tree with single SQL query using CI

To create the N-level Categories tree with single SQL query using CI
class Category_model extends Model {

 private $table = 'categories';
 private $selectTreeOptions_data = null;
 private $selectTreeOptions_index = null;
 
 public function get_categories() {
  $this->db->select('c.id, c.parent_id, c.name');
  $this->db->from($this->table .' AS c');
  $this->db->where('c.status', '1');
  
  $query = $this->db->get();
  //$str = $this->db->last_query();
  
  return $query->result_array();
 }
 
 /*
  * Recursive top-down tree traversal example:
  * Indent and print child nodes
  */
 function getSelectTreeOptions($parent_id, $level, $selected_id='')
 {
  $html = '';
     $data = $this->selectTreeOptions_data;
     $index = $this->selectTreeOptions_index;
     $parent_id = $parent_id === NULL ? 0 : $parent_id;
    
     if (isset($index[$parent_id])) {
         foreach ($index[$parent_id] as $id) {
          $selected = isset($selected_id) && ($selected_id==$data[$id]["id"]) ? 'selected="selected"' : '';
             $html .= '\n";
             $html .= $this->getSelectTreeOptions($id, $level + 1, $selected_id);
         }
     }
          
     return $html;
 }

 // Get the category tree with select options.
 function get_categories_tree_options($selected_id='')
 {
   $categories = $this->get_categories();
  $this->data = '';
  $this->index = '';
  
  foreach ($categories as $row) :
      $id = $row["id"];
      $parent_id = $row["parent_id"] === NULL ? "NULL" : $row["parent_id"];
      $this->selectTreeOptions_data[$id] = $row;
      $this->selectTreeOptions_index[$parent_id][] = $id;
  endforeach;
  
  $items = $this->getSelectTreeOptions(NULL, 0, $selected_id);
  
  return $items;  
 }
 
}

Category_model::get_categories_tree_options($selected_id='');

Wednesday, 15 August 2012

Create Zip File for Multiple files to be downloadable in Codeigniter

define('ROOT_DOWNLOAD_FOLDER_PATH', $_SERVER['DOCUMENT_ROOT']."_files/_downloads/");

function CreateZipFile($zip_folder_name)
{
 $directoryToZip = ROOT_DOWNLOAD_FOLDER_PATH; // This will zip all the file(s) in this present working directory
 $outputDir = ROOT_DOWNLOAD_FOLDER_PATH; //Replace "/" with the name of the desired output directory.
 $this->load->library('ZipFile');
  
 //$this->createzipfile->get_files_from_folder($outputDir, $zip_folder_name.'-');
 $this->zipfile->get_files_from_folder($directoryToZip, '');
 
 //Code toZip a directory and all its files/subdirectories
 $this->zipfile->zipDirectory($directoryToZip, $outputDir);
 
 $fileName = $outputDir.$zip_folder_name.'.zip';

 $fd = fopen ($fileName, 'wb');
 $out = fwrite ($fd, $this->zipfile->getZippedfile());
  
 $this->zipfile->forceDownload($fileName);
 
 @unlink($fileName);
 fclose($fd);
 
 /* Empty directory and remove directory. */
 $directoryToZipPath = $directoryToZip.$zip_folder_name;
 unlinkFolderFiles($directoryToZipPath);
 removeDir($directoryToZipPath);

 exit;
}

$timestamp = date('Y.m.d.h.i.s');
$timestamp = '2012.08.15.12.45.46';
$zip_folder_name = 'Flubit.Inv.All.'.$timestamp;
// For the ZipFile.php, save the below ZipFile.php file content into application/libaries/ZipFile.php
/**
 * Class to dynamically create a zip file (archive) of file(s) and/or directory
 *
 * @author Rochak Chauhan  www.rochakchauhan.com
 * @package CreateZipFile
 * @see Distributed under "General Public License"
 * 
 * @version 1.0
 */

class ZipFile {

 public $compressedData = array();
 public $centralDirectory = array(); // central directory
 public $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record
 public $oldOffset = 0;
 
 function get_files_from_folder($directory, $put_into) {
  if ($handle = opendir($directory)) {
   while (false !== ($file = readdir($handle))) {
    if (is_file($directory.$file)) {
     $fileContents = file_get_contents($directory.$file);
     $this->addFile($fileContents, $put_into.$file);
    } elseif ($file != '.' and $file != '..' and is_dir($directory.$file)) {
     $this->addDirectory($put_into.$file.'/');
     $this->get_files_from_folder($directory.$file.'/', $put_into.$file.'/');
    }
   }
  }
  closedir($handle);
 }
 
 /**
  * Function to create the directory where the file(s) will be unzipped
  *
  * @param string $directoryName
  * @access public
  * @return void
  */ 
 public function addDirectory($directoryName) {
  $directoryName = str_replace("\\", "/", $directoryName);
  $feedArrayRow = "\x50\x4b\x03\x04";
  $feedArrayRow .= "\x0a\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x00\x00\x00\x00";
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("v", strlen($directoryName) );
  $feedArrayRow .= pack("v", 0 );
  $feedArrayRow .= $directoryName;
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $feedArrayRow .= pack("V",0);
  $this->compressedData[] = $feedArrayRow;
  $newOffset = strlen(implode("", $this->compressedData));
  $addCentralRecord = "\x50\x4b\x01\x02";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x0a\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x00\x00\x00\x00";
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("V",0);
  $addCentralRecord .= pack("v", strlen($directoryName) );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("V", 16 );
  $addCentralRecord .= pack("V", $this->oldOffset );
  $this->oldOffset = $newOffset;
  $addCentralRecord .= $directoryName;
  $this->centralDirectory[] = $addCentralRecord;
 }

 /**
  * Function to add file(s) to the specified directory in the archive 
  *
  * @param string $directoryName
  * @param string $data
  * @return void
  * @access public
  */ 
 public function addFile($data, $directoryName)   {
  $directoryName = str_replace("\\", "/", $directoryName);
  $feedArrayRow = "\x50\x4b\x03\x04";
  $feedArrayRow .= "\x14\x00";
  $feedArrayRow .= "\x00\x00";
  $feedArrayRow .= "\x08\x00";
  $feedArrayRow .= "\x00\x00\x00\x00";
  $uncompressedLength = strlen($data);
  $compression = crc32($data);
  $gzCompressedData = gzcompress($data);
  $gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2);
  $compressedLength = strlen($gzCompressedData);
  $feedArrayRow .= pack("V",$compression);
  $feedArrayRow .= pack("V",$compressedLength);
  $feedArrayRow .= pack("V",$uncompressedLength);
  $feedArrayRow .= pack("v", strlen($directoryName) );
  $feedArrayRow .= pack("v", 0 );
  $feedArrayRow .= $directoryName;
  $feedArrayRow .= $gzCompressedData;
  $feedArrayRow .= pack("V",$compression);
  $feedArrayRow .= pack("V",$compressedLength);
  $feedArrayRow .= pack("V",$uncompressedLength);
  $this->compressedData[] = $feedArrayRow;
  $newOffset = strlen(implode("", $this->compressedData));
  $addCentralRecord = "\x50\x4b\x01\x02";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x14\x00";
  $addCentralRecord .="\x00\x00";
  $addCentralRecord .="\x08\x00";
  $addCentralRecord .="\x00\x00\x00\x00";
  $addCentralRecord .= pack("V",$compression);
  $addCentralRecord .= pack("V",$compressedLength);
  $addCentralRecord .= pack("V",$uncompressedLength);
  $addCentralRecord .= pack("v", strlen($directoryName) );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("v", 0 );
  $addCentralRecord .= pack("V", 32 );
  $addCentralRecord .= pack("V", $this->oldOffset );
  $this->oldOffset = $newOffset;
  $addCentralRecord .= $directoryName;
  $this->centralDirectory[] = $addCentralRecord;
 }

 /**
  * Function to return the zip file
  *
  * @return zipfile (archive)
  * @access public
  * @return void
  */
 public function getZippedfile() {
  $data = implode("", $this->compressedData);
  $controlDirectory = implode("", $this->centralDirectory);
  return
  $data.
  $controlDirectory.
  $this->endOfCentralDirectory.
  pack("v", sizeof($this->centralDirectory)).
  pack("v", sizeof($this->centralDirectory)).
  pack("V", strlen($controlDirectory)).
  pack("V", strlen($data)).
  "\x00\x00";
 }

 /**
  *
  * Function to force the download of the archive as soon as it is created
  *
  * @param archiveName string - name of the created archive file
  * @access public
  * @return ZipFile via Header
  */
 public function forceDownload($archiveName) {
  if(ini_get('zlib.output_compression')) {
   ini_set('zlib.output_compression', 'Off');
  }

  // Security checks
  if( $archiveName == "" ) {
   echo "Public Photo Directory - Download 
ERROR: The download file was NOT SPECIFIED."; exit; } elseif ( ! file_exists( $archiveName ) ) { echo "Public Photo Directory - Download
ERROR: File not found."; exit; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=".basename($archiveName).";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($archiveName)); readfile("$archiveName"); } /** * Function to parse a directory to return all its files and sub directories as array * * @param string $dir * @access protected * @return array */ protected function parseDirectory($rootPath, $seperator="/"){ $fileArray=array(); $handle = opendir($rootPath); while( ($file = @readdir($handle))!==false) { if($file !='.' && $file !='..'){ if (is_dir($rootPath.$seperator.$file)){ $array=$this->parseDirectory($rootPath.$seperator.$file); $fileArray=array_merge($array,$fileArray); } else { $fileArray[]=$rootPath.$seperator.$file; } } } return $fileArray; } /** * Function to Zip entire directory with all its files and subdirectories * * @param string $dirName * @access public * @return void */ public function zipDirectory($dirName, $outputDir) { if (!is_dir($dirName)){ trigger_error("CreateZipFile FATAL ERROR: Could not locate the specified directory $dirName", E_USER_ERROR); } $tmp=$this->parseDirectory($dirName); $count=count($tmp); $this->addDirectory($outputDir); for ($i=0;$i<$count;$i++){ $fileToZip=trim($tmp[$i]); $newOutputDir=substr($fileToZip,0,(strrpos($fileToZip,'/')+1)); $outputDir=$outputDir.$newOutputDir; $fileContents=file_get_contents($fileToZip); $this->addFile($fileContents,$fileToZip); } } }
// The below are the basic File and Directory Related functions.
function createFile($filePath='')
{
 try {
  if (!empty($filePath))
  { 
   $ourFileHandle = fopen($filePath, 'w');
   fclose($ourFileHandle);
  }
  return true;
 }
 Catch(Exception $e){ return false; }
}

function unlinkFolderFiles($dir)
{
 $files = getFolderFiles($dir);

 foreach ($files as $file)
 {
  if(file_exists($dir.'/'.$file)) @unlink($dir.'/'.$file);
 }

 return true;
}

function getFolderFiles($dir)
{
 $files = '';
 $ffs = scandir($dir);

 foreach($ffs as $ff)
 {
  if($ff != '.' && $ff != '..')
  {
   $files[] = $ff;
  }
 }

 return $files;
}

function createDir($dir)
{
 if (!is_dir($dir)) {
  mkdir($dir);
 }

 return true;
}

function removeDir($dir)
{
 if (is_dir($dir)) {
  rmdir($dir);
 }
 
 return true;
}

Wednesday, 16 May 2012

Creating Cron-Jobs in CodeIgniter (CI) using CLI - CodeIgniter on the Command Line

To make a Cron Job work in CodeIgniter, you basically need to follow three steps;
  • Create a Model class
  • Create a Cron_Jobs Class
  • Set the Cron-Jobs command in the webserver.
Please, use the below example for the reference.
Step - 1: Create a Model Class.
class Warning_model extends CI_Model {
class Warning_model extends CI_Model {
	public function __construct()
	{
		parent::__construct();
	}
	
	public function addReferenceVATRecord()
	{
		//print_r($_SERVER);die;
		$data = array(	'valid_from' => date('Y-m-d H:i:s'),
						'type_id' => '1',
						'vat_rate' => '22.5',		
						'vat_calc' => '0.27',
						'updated' => date('Y-m-d H:i:s'),
						'updated_by' => '1'
					);
					
		$this->db->insert('reference_vat', $data);
		
		return $this->db->insert_id();
	}
}
/* End of file warning_model.php. */
/* Location: ./application/model/warning_model.php. */
Step - 2: Create a Cron_Jobs Controller Class.
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Cron_Jobs extends CI_Controller {
	
	public function __construct()
	{
		parent::__construct();
		
		$this->load->model('Warning_model', 'm_warning');

		// Call the cron job in below format: 
		// # /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 
	}

	public function cron_update_taxes($action='Cron Jobs')
	{
		echo "Hello {$action}".PHP_EOL;
	}
	
	public function cron_add_vat_record()
	{
		if ( $this->input->is_cli_request() )
		{
			// echo 'Request From CLI';
			$id = $this->m_warning->addReferenceVATRecord();
			echo $id.' '.PHP_EOL; die;
		}
		else { 
			echo 'Sorry Guys, we are bit smart this time.'; die;
		}
		
		//echo $id.' '.PHP_EOL; die;
	}
}
/* End of file cron_jobs.php. */
/* Location: ./application/controller/cron_jobs.php. */
Step - 3: Set the Cron-Jobs command in the webserver.
// Use the Croj Job command in below format: 
# /usr/local/bin/php /home/admin/admincentre.trunk.rc/index.php cron_jobs cron_add_vat_record 

Friday, 11 May 2012

Solution to the problem defining the multiple databases on CodeIgnieter

// Solution to the problem defining the multiple databases on config/database.php on CodeIgnieter
/** Defining Database 1 */
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'dbusername_1';
$db['default']['password'] = 'dbpassword_1';
$db['default']['database'] = 'database_1';
$db['default']['dbdriver'] = 'mysql';
/* ----------
------- */
$db['default']['stricton'] = FALSE;

/** Defining Database 2 */
$db['manage']['hostname'] = 'localhost';
$db['manage']['username'] = 'dbusername_2';
$db['manage']['password'] = 'dbpassword_2';
$db['manage']['database'] = "database_2";
$db['manage']['dbdriver'] = "mysql";
/* ----------
------- */
$db['default']['stricton'] = FALSE;

/** Defining Database 3 */
$db['admin']['hostname'] = "localhost";
$db['admin']['username'] = "dbusername_3";
$db['admin']['password'] = "dbpassword_3";
$db['admin']['database'] = "database_3";
$db['admin']['dbdriver'] = "mysql";
/* ----------
------- */
$db['default']['stricton'] = FALSE;


PS: Please note that, all the databases username/password needs to be unique, if
they have shared the same username/password, then, there may be problem.
Actually, when I tried to use the same username/password for different databases,
I have found that the CodeIgniter is overriding my databases and I have solved it
by assigning unique username/password to each database.

Well, I am not sure, whether its CodeIgniter drawback or not. And, I thought it
would be helpful to share with you as well.

Cheers!

Monday, 26 March 2012

Join Multiple Tables from Multiple Databases in PHP & in Codeigniter


// Join Multiple Tables from Multiple Databases in PHP
PS: You just you use the default database connection to execute the query or you can used either of any database connection if you have already made any other database connection instance. 

// This is for default database connection.
$sqlStr = "SELECT d1t1.id, t1.name, d2t2.no_of_sales, d3t2.customer_type
    FROM db1.Table1 as d1t1, db2.Table1 as d2t1, db3.Table2 as d3t2 
    WHERE d1t1.id='3' AND d3t2.customer_type='sales'";
$result = mysql_query($sqlStr);  
while($row = mysql_fetch_array($result))  {
  echo $id  = $row['id'];
        echo '\n';
        echo $name  = $row['name'];
        ..........
}
In the case of CodeIgniter, please find code below to pull the data from two or multiple database tables.


PS: You just you use the default ($this->db) database connection to execute the query or you can used either of any database connection if you have already made any other database connection instance.

// This is for default database connection.
$this->sqlStr= "SELECT d1t1.id, t1.name, d2t2.no_of_sales, d3t2.customer_type
                   FROM db1.Table1 as d1t1, db2.Table1 as d2t1, db3.Table2 as d3t2
     WHERE d1t1.id='3' AND d3t2.customer_type='sales'";
$query = $this->db->query($this->sqlStr);
$result = $query->row_array(); 
print_r($result);

Wednesday, 21 March 2012

Create Multiple Databases Connections in Codeigniter


// To connect to Multiple Databases Connection in Codeigniter
// Open config/database.php and build the db connection array.

// This is for default database.
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'db_default';
........
.......

// This is for second database database.
$db['db2']['hostname'] = 'localhost';
$db['db2']['username'] = 'root';
$db['db2']['password'] = '';
$db['db2']['database'] = 'database2';
........
.......
Now, open your model files and create the db instance as per needs for second database.

class Rc_model extends CI_Model {
 private $db2; 
 public function Rc_model()
 {
  parent::__construct();
  // $this->db; // this is for default database connection.
  // $this->db = $this->load->database(); // this is also for default connection if you need a db instance.
  // Creating the db object for Second Database whose connection is available globally.
  $this->db2 = $this->load->database('db2', TRUE);
  $this->db2 =& $this->db2;
 }

 public function GetAllCategories()
 {
  $query = $this->db2->get_where('categories_table', array('active'=>'1'));
  return $query->result();
 }
}