Codeigniter - I am looking to use/connect to a different database for one of my controllers and one model


Question

I am looking to use/connect to a different database for one of my controllers and one model. I posted this hear since on the forums of CI I am getting no response.

I added this in database.php:

$db['tdb']['hostname'] = "localhost";//localhost

$db['tdb']['username'] = "username";//root

$db['tdb']['password'] = "password";//empty

$db['tdb']['database'] = "databasename";

$db['tdb']['dbdriver'] = "mysql";

$db['tdb']['dbprefix'] = "";

$db['tdb']['pconnect'] = FALSE;

$db['tdb']['db_debug'] = FALSE;

$db['tdb']['cache_on'] = FALSE;

$db['tdb']['cachedir'] = "";

$db['tdb']['char_set'] = "utf8";

$db['tdb']['dbcollat'] = "utf8_general_ci";

This as my model:

<?php

class Tadmin_model extends Model{

    function Tadmin_model(){

        parent::Model();

        $tdb = $this->load->database('tdb', TRUE);            
    }

    function FInsert($usernames){

        $query = $tdb->query("SELECT * FROM following");

        return $query->row();
    }    
}

?>

And this is the start of my controller:

<?php

class Tadmin extends Controller{

    function Tradmin(){

        parent::Controller();

        $this->load->model('tadmin_model');

And I get this error:

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: tdb

Filename: models/tadmin_model.php

Line Number: ...

Fatal error: Call to a member function query() on a non-object in /blablabla/tadmin_model.php on line ...

What am I doing wrong here?

1
1
12/30/2012 2:21:46 PM

Your issue here isn't with the use of CodeIgniter's database functions, but with variable scoping in classes. When you load your model you're connecting to the database and assigning the result to a local variable in the model's constructor. When any function finishes, the local variables are discarded. Later you try to call the query() method on the $tdb variable which has already been thrown away and get an error.

You need to store the results of $this->load->database() in a location which is available to both the constructor and the method. You could move the $this->load->database() call into the controller method and connect to the other database every time you call the Tradmin method on your model.

The other way if you wanted to make $tdb available to all methods in the model is to use a member variable on the class, which would look like this....

<?php

class Tadmin_model extends Model{
    var $tdb;

    function Tadmin_model(){

        parent::Model();

        $this->tdb = $this->load->database('tdb', TRUE);            
    }

    function FInsert($usernames){

        $query = $this->tdb->query("SELECT * FROM following");

        return $query->row();
    }    
}

?>

Hope that helps.

Jim.

5
12/5/2008 3:18:04 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon