0

I am new to Codeigniter and trying to connect to dynamic database define by user, like we normally do in PHP.

Currently i am able to connect to database by using the setting mention in user guide and trying to access it like..

class ModelTest extends CI_Model
{
    public function getdata()
    {
        $this->load->database();
        $q=$this->db->query("SELECT * FROM users");
        return $q->result();

    }

}

Now i want to access it using the database define by the user, not the default like we use normally..

class Database{

    // specify your own database credentials
    private $host = 'mysql:host=localhost;dbname=satudent_enrollement';
    private $username = 'root';
    private $password = '';
    public $conn;

    // get the database connection
    public function getConnection(){

        $this->conn = null;

        try{
            $this->conn = new PDO($this->host , $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

What I Want: To connect the Database using the database define by the user not the default.

Any help will be appreciated.

2
  • which version of codeigniter is this? Commented Aug 5, 2016 at 10:39
  • latest version 3.1.0 Commented Aug 5, 2016 at 10:52

2 Answers 2

1

According to the Codeigniter User Guide, you can manually pass database connectivity settings via the third parameter of $this->load->model:

$config['hostname'] = "mysql:host=localhost";
$config['username'] = "root";
$config['password'] = "XXX";
$config['database'] = "satudent_enrollement";
$config['dbdriver'] = "pdo";
$config['dbprefix'] = "";
$config['pconnect'] = FALSE;
$config['db_debug'] = TRUE;

$this->load->model('ModelTest', '', $config);

// or as gorelative notes, to access multiple databases:

$DB2 = $this->load->database($config, TRUE);

I hope it will work for you!!

Sign up to request clarification or add additional context in comments.

Comments

0

Use below setting in database.php for PDO in 2.x version

$db['default']['hostname'] = 'mysql:host=localhost';
$db['default']['dbdriver'] = 'pdo';
$db['default']['database'] = 'satudent_enrollement';

hope it helps

2 Comments

Thanks for your effort, but this is the default setting and it is working for me, i want the user define.. please read the question again.
Yhea den create a file and put in core which extends the default core and do your custom codings in that file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.