CodeIgniter - 在Helper中访问数据库

Dea*_*der 1 php codeigniter

我在我的视图中有这个代码.

$country = array(
    'id' => 'country',
    'name' => 'country',
    'value' => get_user_info('country'),
    'size' => 30
);

<tr>
            <td><?php echo form_label('Country', $country['id']); ?></td>
            <td><?php echo form_input($country); ?></td>
            <td style="color: red;"><?php echo form_error($country['name']); ?><?php echo isset($errors[$country['name']])?$errors[$country['name']]:''; ?></td>
    </tr>
Run Code Online (Sandbox Code Playgroud)

get_user_info()是我的form_helper中定义的函数,如下所示:
Form_Helper.php

if(! function_exists('get_user_info')){

        function get_user_info($field)
        {
            $ci = & get_instance();
            $ci->load->model('users');
            return $ci->users->get_user_profile($field);
        }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,在此函数内部,我通过用户模型访问数据库.User_Model

function get_user_profile($field)
        {
            $user_id = $this->session->userdata('user_id');

            $this->db->select($field);
            $this->db->where('user_id',$user_id);

            $query = $this->db->get($this->profile_table_name);
            if($query->num_rows()==1)return $query->row();

            return NULL;
        }
Run Code Online (Sandbox Code Playgroud)

我们的想法是在页面加载时自动填充表单的Country字段.
但在视图中我收到此错误

A PHP Error was encountered

Severity: Warning

Message: htmlspecialchars() expects parameter 1 to be string, object given

Filename: helpers/form_helper.php

Line Number: 646
Run Code Online (Sandbox Code Playgroud)

可能是什么问题?
谁能知道发生了什么?或者过去曾有人做过这样的事吗?
它是在辅助函数中访问模型的正确方法吗?

谢谢

编辑
为了做得更好更快,我只需从控制器中调用模型,然后将不同的值传递给视图.
调节器

$d = $this->users->get_user_profile('country, telephone, city, street, address, town');
        $d2 = Array(
            'telephone' => $d->telephone,
            'country' => $d->country,
            'city' => $d->city,
            'street' => $d->street,
            'address' =>$d->address,
            'town' => $d->town);
        $this->template->write_view('contentw','dashboard/profile', $d2);
        $this->template->render();
Run Code Online (Sandbox Code Playgroud)

所以我删除了我添加到Helper文件中的函数.

这种方法对我有用.
谢谢大家的答案

Mur*_*ski 6

通常,帮助程序用作全局函数来执行一些简单的工作.大多数人会说在帮助程序中调用模型是错误的.应该像PHP函数一样使用助手explode; 它有一个任务,接收输入,并根据输入非常机械地提供输出.

控制器可能更好地访问模型并获取该值,然后将其传递到视图中并直接使用它

至于错误:

您可能正在收到该错误,因为您正在返回$query->row()而不是该字段中的实际值. $query->row()很可能是一个对象,$query->row()->country是实际值