php - 在 Controller 中使用模型函数

标签 php mysql codeigniter

在名为 Profile_model 的模型中,我有一个函数可以检索登录用户的个人资料数据。

function profile_read()
{
    $this->db->where('user_id', $this->tank_auth->get_user_id());
    $query = $this->db->get('user_profiles');
    $data['row'] = $query->row();
}

在我的 Controller 中,我使用 $this->load->view('profile/edit_general_view', $data); 尝试将数据从模型加载到 View 中。

function edit_profile()
{       

    //validation rules
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');
    $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');


    if ($this->form_validation->run() == FALSE) //if validation rule fails
    {           
        $this->load->view('profile/edit_general_view', $data); //load data from model in view
    }
    else //success
    {
        $send_to_db = array (                   
                'first_name'    => $this->input->post('first_name'),
                'last_name'     => $this->input->post('last_name')
        );
        $seg = 'edit';
        $this->load->model('Profile_model');
        $this->Profile_model->profile_update($send_to_db, $seg);            
    }
}

将数据从模型函数 profile_read 传递到我的 Controller 函数的正确方法是什么?

最佳答案

是时候了解变量作用域了: http://php.net/manual/en/language.variables.scope.php

Controller 无法访问模型方法中的 $data 变量。让模型方法返回实际的数据数组..例如:

function profile_read()
{
    $this->db->where('user_id', $this->tank_auth->get_user_id());
    $query = $this->db->get('user_profiles');
    return ($query ? $query->row : FALSE);
}

然后在 Controller 中,将其存储在 View 的“数据”中。

关于php - 在 Controller 中使用模型函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6218265/

相关文章:

mysql - 访问mysql中的计数值

php - 在 PHP 中对具有特殊字符的数组进行排序

php - 如何从具有相同 id 的 2 个或多个条件的 2 个表中进行选择

php - 在 Web 服务器 PHP 上验证订单的 InApp 计费

mysql - 从 2 个表中选择相同列到 View 中的 1 列中

java - 将外部 jar 添加到 ModCoderPack (MCP)

php - 显示使用 codeigniter 中的一对多关系存储的数据库中的图像

linux - codeigniter自动加载文件问题

javascript - 通过 ajax 将 Javascript 变量传递给 PHP

php - 为 PHP 数组分配索引