Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access DB config in CodeIgniter?

Tags:

codeigniter

In my application, I need to know what values are assigned to the DB config items such as database, username, etc. How do I access those information?

like image 926
StackOverflowNewbie Avatar asked Dec 07 '11 09:12

StackOverflowNewbie


People also ask

Where is DB config file?

The config file is located at app/Config/Database.

How manually connect to database in CodeIgniter?

Manually Connecting to a Database To choose a specific group from your config file you can do this: $this->load->database('group_name'); Where group_name is the name of the connection group from your config file.

Where is config database php?

The database configuration file is app/config/database. php . In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file.

What is DB config?

You use the Database Configuration application to create or change objects and attributes, and to customize the database. An object is a self-contained software entity that consists of both data and functions to manipulate data.


3 Answers

I don't have enough rep to comment on Matt Browne's correct answer but just adding a bit incase anyone forgets...

load the db driver like so first:

$this->load->database();

then you can easily access what you need:

$this->db->hostname
$this->db->username
$this->db->password
$this->db->database
like image 86
Chris B Avatar answered Oct 15 '22 18:10

Chris B


Pretty much all the config values are accessible via $this->db (take a look at system/database/DB_driver.php).

That's what worked for me...none of the other suggestions here did.

As an example

$config = [ 
     'host'     => $this->db->hostname,
     'port'     => '3306',
     'username' => $this->db->username,
     'password' => $this->db->password,
     'database' => $this->db->database
];
like image 40
Matt Browne Avatar answered Oct 15 '22 20:10

Matt Browne


In case you have multiple database connection groups defined in config/database.php, for eg :

  $db['dbname']['hostname'] = "localhost";
  $db['dbname']['username'] = "root";
  $db['dbname']['password'] = "root";
  $db['dbname']['database'] = "web_dbname";

  $db['dbname_readonly']['hostname'] = "localhost";
  $db['dbname_readonly']['username'] = "root";
  $db['dbname_readonly']['password'] = "root";
  $db['dbname_readonly']['database'] = "web_dbname_readonly";

If you want to use the connection params of any particular db in a controller or model:

  $db = $this->load->database('dbname');

If you want to use in a helper or library :

  $ci = &get_instance();
  $db = $ci->load->database('dbname');

The connection params will be available as $db->hostname, $db->username etc.

like image 42
s1d Avatar answered Oct 15 '22 20:10

s1d