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?
The config file is located at app/Config/Database.
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.
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.
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.
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
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
];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With