Is it possible to get the database.php variables values from a helper in Codeigniter?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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).
}
回答2:
$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);
回答3:
My easiest fix was
include_once APPPATH . 'config/database.php';
echo json_encode($db); // contains all the database configurations