在codeigniter中访问控制器中发布的变量

时间:2015-04-05 18:28:52

标签: php codeigniter

我对codeigniter非常陌生,我正在构建一些示例工具来了解我的方法。我现在已经按照自己的方式在线阅读了一些基本的教程。

我已经获得了以下代码,我试图在注册之前确定用户是否存在。我也无法告诉我如何判断用户是否已经存在,如果它出现错误,我该将数据传回去哪里?

我得到的错误是:

致命错误:在第18行的/Users/Tom/www/crm/application/helpers/site_helper.php中不在对象上下文中时使用$ this

控制器/ users.php

public function register()
    {
        $this->load->helper('form');
        $this->load->library('form_validation');

        $data['title'] = 'Create a new user';

        $this->form_validation->set_rules('firstname', 'First Name', 'required');
        $this->form_validation->set_rules('surname', 'Surname', 'required');

        if ($this->form_validation->run() === FALSE)
        {
            $this->load->view('templates/header', $data);
            $this->load->view('users/register');
            $this->load->view('templates/footer');

        }
        else
        {
            if(c_userexists($this->input->post('email'))){
                $this->load->view('templates/header', $data);
                $this->load->view('users/register');
                $this->load->view('templates/footer');
            } else {
                $this->users_model->set_register();
                $this->load->view('users/success');
            }
        }
    }

助手/ site_helper.php

   if(!function_exists('c_userexists'))
    {
        function c_userexists($value)
        {
            $this->db->select('count(*) as user_count');
            $this->db->from('users');
            $this->db->where('email', $userId);

            $query = $this->db->get();
            if($query > 0){
                return true;
            } else {
                return false;
            }
        }
    }

模型/ Users_model.php

public function set_register()
    {
        $this->load->helper('url');

        $data = array(
            'firstname' => $this->input->post('firstname'),
            'surname' => $this->input->post('surname'),
            'email' => $this->input->post('email'),
            'password' => c_passencode($this->input->post('email'))
        );

        return $this->db->insert('users', $data);
    }

1 个答案:

答案 0 :(得分:0)

$this是对控制器对象实例的引用。您无法直接在辅助函数中引用$this。您可以使用get_instance帮助程序函数来访问当前运行的控制器实例的实例。

简而言之,请更新您的site_helper:

if(!function_exists('c_userexists'))
{
    function c_userexists($value)
    {
        $CI =& get_instance();
        $CI->db->select('count(*) as user_count');
        $CI->db->from('users');
        $CI->db->where('email', $userId);

        $query = $CI->db->get();
        if($query > 0){
            return true;
        } else {
            return false;
        }
    }
}

有关更多信息,请查看: http://www.codeigniter.com/userguide3/general/ancillary_classes.html?highlight=get_instance#get_instance

相关问题