简体   繁体   中英

How can I connect mysql database dynamically with different values of host name,username , password

I have a common database table which contain different db name of different clients . I need connect dynamically these db as I get the value of hostname,username and password from query . I am using codeigniter and php7.2. Please need some suggetion . Thanks in advance.

In CI you can do by two ways.

  1. From config/database.php

    you can call default db to fetch rows and run in loop with dynamic key assign. As required you can call that db credential.

  2. From Model or controller.

    $this->load->database(array( 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'ci', 'dbdriver' => 'mysqli', ));

You could create a helper that loads your dynamic database and call it on your model.

Helper:

if (!function_exists('get_dynamic_db')){
    function get_dynamic_db()
    {
        $CI =& get_instance();
        $db = $CI->session->user_data('other_db');
        $user = $CI->session->user_data('user');
        $pass = $CI->session->user_data('pass');

        $config_app = array(
            'dsn'   => '',
            'hostname' => 'localhost',
            'username' => $user,
            'password' => $pass,
            'database' => $db,
            'dbdriver' => 'mysqli',
            'dbprefix' => '',
            'pconnect' => FALSE,
            'db_debug' => (ENVIRONMENT !== 'production'),
            'cache_on' => FALSE,
            'cachedir' => '',
            'char_set' => 'utf8',
            'dbcollat' => 'utf8_general_ci',
            'swap_pre' => '',
            'encrypt' => FALSE,
            'compress' => FALSE,
            'stricton' => FALSE,
            'failover' => array(),
            'save_queries' => TRUE
        );

        return $CI->load->database($config_app,TRUE);
    }
}

Sample Model:

var $dynamic_db;

public function __construct() {

    $this->load->database(); //ur regular DB -- $this->db
    $this->dynamic_db = get_dynamic_db(); //ur dynamic DB -- $this->dyniamic_db
}

public function ping_dynamic_db()
{
    $this->dynamic_db->from('some_table');
    $query = $this->dynamic_db->get();

    return $query->row();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM