0

I need 3 database connections with Codeigniter. I don't know any information about host, username or password of those databases. this means the user has to send these information using a form.

What I know, is that can add another array such as $db['another_db'] to config/database.php but how would I set the values of hostname, username and password dynamically?

I tried to use an own class to do this but i's not really working:

<?php
class Connection_model extends CI_Model {
    public function define_database($member, $host, $user, $pw, $database) {
        $db[$member] = array(
                'dsn'   => '',
                'hostname' => $host,
                'username' => $user,
                'password' => $pw,
                'database' => $database,
                'dbdriver' => 'mysqli',
                'dbprefix' => '',
                'pconnect' => FALSE,
                'db_debug' => TRUE,
                'cache_on' => FALSE,
                'cachedir' => '',
                'char_set' => 'utf8',
                'dbcollat' => 'utf8_general_ci',
                'swap_pre' => '',
                'autoinit' => TRUE,
                'encrypt' => FALSE,
                'compress' => FALSE,
                'stricton' => FALSE,
                'failover' => array(),
                'save_queries' => TRUE
        );
    }

    public function get_person($member, $host, $user, $pw) {
        $otherdb = $this->load->database($this->define_database($member, $host, $user, $pw, $database), TRUE);

        $query = $otherdb->select('first_name, last_name')->get('person');
        var_dump($query);
    }
}

And I use it on my controller like this:

    $this->load->model('connection_model');
    $this->connection_model->get_person('sender', 'localhost', 'root', '', 'test');

I get the message: Undefined variable: database

What am I doing wrong? Or is there another way to get another connection?

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

0

Look at your get_person method, it takes 4 arguments:

public function get_person(**$member, $host, $user, $pw**) 

but inside of that You call the method define_database passing 5 arguments:

$this->define_database($member, $host, $user, $pw, **$database**)

CI gives error because fifth argument is not defined in this scope.

  • Oh, what a stupid mistake. Thank you, I changed it but now I get another error: You have not selected a database type to connect to. So how can select that database? –  Feb 05 '15 at 16:33
  • I think the problem is here: $otherdb = $this->load->database($this->define_database($member, $host, $user, $pw, $database), TRUE); Your define_database method doesn't return anything, so load->database take null argument Try to write: return $db[$member]; At the end of define_database method – Shynggys Kengessov Feb 05 '15 at 16:36
  • You're right! I added return $db[$member] to my define_database function and it works now. Thank you so much! –  Feb 05 '15 at 16:40