van_folmert
van_folmert

Reputation: 4507

How to access database in library class?

I'm rewriting my application to make use of CodeIgniter. Currently I'm struggling with DB. I've configured databases in config/databases.php but have no idea how to access them at a library level.

I'm loading libraries via autoload.php:

$autoload['libraries'] = array('database', 'FGMembersite', 'phpmailer', 'formvalidator');

FGMembersite is a class which I'm using for registration and login.
I access this class in login.php view where I have:

if(isset($_POST['submitted']))
{
   if($this->fgmembersite->Login())
   {
        $this->fgmembersite->RedirectToURL("main");
   }
}

fgmembersite->Login() leads to:

public function DBLogin()
{

  $this->connection = pg_connect("host=localhost port=5432 dbname=".$this->db->database." user=".$this->ci->db->username." password=".$this->db->password."");

but DBLogin() here doesn't understand what is db . I receive errors like
Undefined property: FGMembersite::$db
or
Trying to get property of non-object

How I'm supposed to access database config in my FGMembersite?

Upvotes: 2

Views: 231

Answers (1)

Re0sless
Re0sless

Reputation: 10886

You need to use the CodeIgniter super object to gain access to the auto loaded libraries, from within other libraries. Like so

$ci =& get_instance();

$this->connection = pg_connect("host=localhost port=5432 dbname=" . $ci->db->database . 
                               " user=" . $ci->db->username . 
                               " password=" . $ci->db->password );

It looks like you were trying to use this method in your code, except you only used it for the username field, not the database and password ones.

You can save the ci instance by assigning it to a class property in your classes constructor, like so:

class Yourclass {

    private $ci;

    public function __construct() {

        $this->ci =& get_instance();  

    }

    public DBLogin() {

         $this->connection = pg_connect("host=localhost port=5432 dbname=" .
                             $this->ci->db->database . 
                               " user=" . $this->ci->db->username . 
                               " password=" . $this->ci->db->password );
    }

    public somethingElse() {

        print_r ($this->ci->db->username);

    }

}

Upvotes: 2

Related Questions