Skip to content

PEAR MDB2 In Codeignitor

World Wide Web Server edited this page Jul 4, 2012 · 26 revisions

[h3]Download[/h3] File:MDB2.zip


I use codeigniter frequently for my project, but what i always need to do is use Pear MDB2 insist of codeigniter ADR, so below is some simple step by which you can use PEAR MDB2 in your codeigniter framework.

Step 1 : Install Pear and add pear folder in your php.ini files require option.

Step 2 : if you already added the database in your autoload.php file for autoloading of your database so pls remove it.

Step 3 : Create one directory named 'pear' in application folder.

Step 4 : Unzip the attached file in the same folder i.e : application/pear what is in the attachment?? nothing but just a MDB2 files with all supported database driver, provided by pear.php.net with latest version. So that's you wont need to copy each driver separately in that folder. Now your file structure like application/pear/MDB2/MDB2.php (mdb2 class file) application/pear/MDB2/MDB2/ (all database driver in it)

Step 5 : Create file named 'Mdb2loader.php' in application/libraries folder. Add below code in the same file

[code]<?php
    if (!defined('BASEPATH')) exit('No direct script access allowed');
class Mdb2loader{        
  function connectdb(){
    require_once "".APPPATH."/pear/MDB2/MDB2.php";
    $dsn = 'mysql://username:password@localhost/database_name';
    $mdb2 =& MDB2::factory($dsn);
    if (PEAR::isError($mdb2)) {
        die($mdb2->getMessage());
    }
    return $mdb2;    
}

} ?>[/code] HERE adjust $dsn value as per your setting

Setp 6 : Create new controller name Welcome Add below codes in that file

[code]<?php class Welcome extends Controller { private $db2; function __construct() { parent::Controller();
$this->load->library('Mdb2loader'); return $this->db2 = $this->mdb2loader->connectdb(); }

function index(){
    $sql = $this->db2->query('SELECT * FROM db_table');
    if (PEAR::isError($sql)) {
        die($sql->getMessage());
    }

    echo "<table>";
    while (($row = $sql->fetchRow())) {
            echo "<tr>";
            echo "<td>".$row['0']."</td>";
            echo "<td>".$row['1']."</td>";
            echo "<td>".$row['2']."</td>";
        echo "</tr>";        
    }
    echo "</table>";
    $sql->free();
}

}[/code] Adjust the database table name in above query.

Done :: now check the working status of your controller

[h3]Download[/h3] File:MDB2.zip

Clone this wiki locally