php 从 Codeigniter 中的助手访问数据库配置变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7242413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access database config variables from a helper in Codeigniter
提问by razorfish
Is it possible to get the database.php variables values from a helper in Codeigniter?
是否可以从 Codeigniter 中的助手获取 database.php 变量值?
回答by Muhammad Usman
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.
这是方法,通常您将无法$this
在 helper 中使用,因此您必须使用get_instance()
. 我已经给出了一个“主机名”的例子,你可以使用你需要的配置名称。
function test()
{
$CI =& get_instance();
$CI->load->database();
echo $CI->db->hostname; // give the config name here (hostname).
}
回答by Tobias
$ci=& get_instance();
$ci->config->load('database');
$ci->config->item('item name');
Ifyou want to access the config file for the database when $this->config->load(); is not available, the solution could look like this:
如果你想在 $this->config->load(); 时访问数据库的配置文件;是不可用,则解决方案看起来是这样的:
include(APPPATH.'config/database'.EXT);
$conn = mysql_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password']);
mysql_select_db($db['default']['database'], $conn);
回答by Abel Callejo
My easiest fix was
我最简单的解决方法是
include_once APPPATH . 'config/database.php';
echo json_encode($db); // contains all the database configurations