14

Is it possible to get the database.php variables values from a helper in Codeigniter?

Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
Thomas Makos
  • 1,648
  • 3
  • 13
  • 15

3 Answers3

30

Here is the way, normally you won't be able to use $this in helper, so you have to use get_instance(). I have given an example of 'hostname' you can use the config name you need.

   function test()
    {
        $CI =& get_instance();
        $CI->load->database();
        echo $CI->db->hostname; // give the config name here (hostname).
    }
Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
11
$ci=& get_instance();
$ci->config->load('database');
$ci->config->item('item name');

If you want to access the config file for the database when $this->config->load(); is not available, the solution could look like this:

include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);

mysql_select_db($db['default']['database'], $conn);
Tobias
  • 491
  • 3
  • 10
  • Another one is still there "If you want to access the config file for the database when `$this->config->load();` " Thanks – Muhammad Usman Aug 30 '11 at 12:14
  • Usman, read the last section of that sentence. IF $this and get_instance(); is NOT available, you can load the config file with that code. (For an example, if you're creating a MY_Security.php) – Tobias Aug 30 '11 at 12:16
1

My easiest fix was

include_once APPPATH . 'config/database.php';
echo json_encode($db); // contains all the database configurations
Abel Callejo
  • 13,779
  • 10
  • 69
  • 84