【问题标题】:CodeIgniter - Access database within a HelperCodeIgniter - 在 Helper 中访问数据库
【发布时间】:2012-10-14 15:54:01
【问题描述】:

我的视图中有这段代码。

$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>

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);
        }
}

如您所见,在此函数中,我通过 users 模型访问数据库。 用户模型

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;
        }

这个想法是在页面加载时自动填写表单的 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

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

谢谢

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

$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();

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

这个方法对我有用。
谢谢大家的回答

【问题讨论】:

  • 你为什么要加载,如何在你的助手中建模?然后是 SESSION 检查和 DB 查询……设置这样的“帮助”很糟糕!

标签: php codeigniter


【解决方案1】:

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

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

至于错误:

您可能会收到该错误,因为您返回的是$query-&gt;row(),而不是该字段中的实际值。 $query-&gt;row() 很可能是一个对象,$query-&gt;row()-&gt;country 是实际值

【讨论】:

【解决方案2】:

据我所知,助手并没有被 CI 的其他部分所吸引。我确信有一些方法可以让它们像那样工作,但也许只创建一个库会更有效率?

如果您创建了一个库,您可以通过&amp;=get_instance(); 访问 CI 中的所有重要内容,并且不会有太大的不同。您可以创建一个用户库并像这样调用它:

$this->load->library('users');

$this->users->get_user_info('country');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 1970-01-01
    相关资源
    最近更新 更多