CodeIgniter全局设置数据库


CodeIgniter global settings database

我正在尝试实现每个控制器和视图的全局设置。

数据库表名为config包含

config_name | config_value
title        | My Website
email       | my@example.com
我在<<p> strong> 模型 我有查询:
function config()
{
    $query = $this->db
        ->select('*')
        ->get('config');
    return $query->result();
}

controller我这样调用模型数据

$data['cfg'] = $this->config_model->config();

现在我想通过使用

视图中显示配置的某些位
<title><?php echo $cfg->title; ?></title>

但是我得到一个错误试图获得非对象的属性

我尝试了模型中的结果查询选项 query:

result();
result_array();

但它不会工作。我做错了什么?

在你的模型中试试:

public function config() {
  $q = $this->db->get('config')
return $q->result_array();

在你的控制器中:

$this->load->model("config_model");
    $res = $this->config_model->get();
    if($res){
        $data['result'] = $res;
        $this->load->view('Your view here', $data);
    } else {
        echo "failed";
    }

然后你可以在视图中这样访问:

$result[0]['title'];

假设你的配置表只有一行

好了,我已经把事情简化了,并这样解决了:

修改数据库表布局为1行

title | email | country | city

现在它工作了。以前我想要db布局不同,但我现在要这样做。

可以这样使用

你的模型:

public function get() {        
$query = $this->db->get('config');        
if ($query->num_rows() > 0) 
{
    foreach ($query->result() as $row) 
    {
        $data[$row->item] = $row->val;
    }                      
    return $data;
} 
return false; 
}

在控制器中使用:

$this->load->model("config_model");           
$config = $this->config_model->get(); 
echo $config['title'];

use in view:

$this->load->view('index',$config); 
结果:

<p><?=$title?></p>