在codeigniter中登录错误消息验证

时间:2018-05-15 06:09:58

标签: php codeigniter

如果用户没有输入用户名和密码并尝试点击登录,我试图显示错误消息。我试图显示错误消息,如用户名未输入和密码未输入。但它没有完美运作。

这是我的控制器:

public function login_user() {

    //$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean','required');
    //$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean','required');

    if ($this->form_validation->run() == FALSE) {

        $this->load->view('login_view');
    } else {
        $data = array(
            'username' => $this->input->post('username'),
            'password' => $this->input->post('password'),
            'firstname' => $this->input->post('firstname'),
            'lastname' => $this->input->post('lastname')
        );
        $result = $this->login_database->login($data);
        if ($result == TRUE) {
                    // Add user data in session
            $this->session->set_userdata('username', $data['username']);
            $this->session->set_userdata('firstname', $data['firstname']);
            $this->session->set_userdata('lastname', $data['lastname']);

            //redirect to dashboard
            $this->load->view('include/sidenavbar');
            $this->load->view('include/topnavbar');
            $this->load->view('dashboard');
        } else {
            if($data['username']=='')
            {
               $this->session->set_flashdata('err_message', 'Username Not Entered !');
            }

            $this->session->set_flashdata('err_message', 'Login is invalid. Please try again !');
            $this->load->view('login_view', $data);
        }
    }
}

这是我的模特:

public function login($data) {

    $condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "'";
    $this->db->select('*');
    $this->db->from('users');
    $this->db->where($condition);
    $this->db->limit(1);
    $query = $this->db->get();

    if ($query->num_rows() == 1) {
        return true;
    } else {
        return false;
    }
}

查看:

<?php 
if( $this->session->flashdata('err_message') )
{
    echo $this->session->flashdata('err_message');
}
?>

任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:3)

请通过传递如下所示的数组来尝试该消息。

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

$this->session->set_flashdata('err_message', array('message' => 'Username Not Entered','class' => 'alert alert-warning'));

感谢。

答案 1 :(得分:1)

我尝试了这样,然后它的工作完美。

查看:

  <?php echo form_error('username','<span class="error">','</span>'); ?>
                    <input type="text" name="username" placeholder="Username" />
                     <?php echo form_error('password','<span class="error">','</span>'); ?>
                    <input type="password" name="password" placeholder="Password" />

我使用form_error来显示每个字段的错误。

然后它完美地运作。

相关问题