CodeIgniter Forums
multiple databases connectivity - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: multiple databases connectivity (/showthread.php?tid=69139)



multiple databases connectivity - nadeem14375 - 10-12-2017

I have the following code in model to connect to another database.


PHP Code:
        $db_name $this->session->userdata('db_name');
        $this->anotherDb $this->load->database($db_nameTRUE); 

but if I try to query in another model using the anoterDb using the following:

PHP Code:
        $query=$this->anotherDb->query("SELECT fieldValue
                                 FROM settings
                                 WHERE fieldName ="
."'".$fieldName."'"
                                 )->row_array();
                      $fieldValue $query['fieldValue']; 

error:
Quote:Message: Undefined property: Users::$anotherDb

to remove this error I need to reconnect to above database "anotherDb" in every model.
How can I solve this?


How can I make some global variable to be used in every model?


RE: multiple databases connectivity - dave friend - 10-13-2017

To make the alternate database available to multiple models make the property $anotherDb a member of the controller. Set the property in the controller's constructor.

PHP Code:
Class Welcome extends CI_Controller
{
   public $anotherDb;

   function __construct()
   {
       parent::__construct();
       $db_name $this->session->db_name;
       if(isset($db_name))
       {
            $this->anotherDb $this->load->database($db_nameTRUE);
        }
        else
        {
              throw new Exception('Second database name not found.');
         }
   



RE: multiple databases connectivity - nadeem14375 - 10-15-2017

Thanks