Activated PDO in CodeIgniter

Because being popular use PDO lately, so yesterday I tried to find out how to use PDO in CodeIgniter. And in some time, I finally managed to also use PDO in CodeIgniter. Ok now I will try how to connected CodeIgniter with database using PDO. Look this instructions:

  1. Firs. Open your CodeIgniter application. Open yourci/application/config/database.php and change like this:
    $active_group = 'default';
    $active_record = TRUE;
    
    $db['default']['hostname'] = 'pgsql:host=localhost;dbname=yourdb'; //if you are use mysql change to 'mysql:host=localhost;dbname=yourdb';
    $db['default']['username'] = 'your username';
    $db['default']['password'] = 'your password';
    $db['default']['database'] = 'your database';
    $db['default']['dbdriver'] = 'pdo';
    $db['default']['dbprefix'] = '';
    $db['default']['pconnect'] = TRUE;
    $db['default']['db_debug'] = TRUE;
    $db['default']['cache_on'] = FALSE;
    
  2. And for example, you must create example database. This is example structure my database:
    spp_darulhikmah=> \d siswa;
                 Table "public.siswa"
      Column  |         Type          | Modifiers 
    ----------+-----------------------+-----------
     no_induk | integer               | not null
     nama     | character varying(50) | not null
     kelas    | character varying(5)  | not null
    Indexes:
        "pk_siswa" PRIMARY KEY, btree (no_induk)
    
  3. And open yourci/application/controllers/, and create example controllers like this (c_test.php):

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    class C_test extends CI_Controller {
    	public function index() {
    		$noInduk = '2010140419';
    		$sql = "SELECT * FROM siswa WHERE no_induk = ?";
    
    		$q = $this->db->conn_id->prepare($sql);
    
    		//binding option using PDO
    		$q->bindValue(1, $noInduk, PDO::PARAM_INT);
    		$q->execute();
    		print_r($q->fetch(PDO::FETCH_ASSOC));
    	}
    }
    /* End of file c_test.php */
    /* Location: ./application/controllers/c_test.php */
    
  4. The last, open your browser and open url http://localhost/yourci/index.php/c_test and I get result such as:

    Array
    (
    [no_induk] => 2010140419
    [nama] => Imron Rosdiana
    [kelas] => VII
    )

For more information about PDO, you can read from http://php.net/manual/en/book.pdo.php

Advertisements

4 comments

  1. I am using codeigniter 2.2.0, should I add or load any particular driver in codeigniter to use PDO function? Thx in advance..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s