Umut Bulut Umut Bulut - 9 days ago 5
MySQL Question

codeIgniter how can i create session into login controller

How can I create login session name? I tried but it didn't work for me.

Here is my code:

loginModel

public function login($name, $pass){
$this->db->select("username", "password");
$this->db->from("users");
$this->db->where("username", $name);
$this->db->where("password", $pass);
$query = $this->db->get();
$ret = $query->row();
if($query->num_rows() == 1){
return true;
}
else {
return false ;
}
}


loginControler;

public function checkLogin(){
$this->form_validation->set_rules("username", "Username", "required");
$this->form_validation->set_rules("password", "Password", "required");
if($this->form_validation->run() == false){
$this->load->view("login");
}
else {
redirect("SiteCont/index");
}
}

public function verifyUser(){
$name = $this->input->post("username");
$pass = $this->input->post("password");
$this->load->model("loginModel");
if($this->loginModel->login($name, $pass)){
return true;
}
else {
$this->form_validation->set_message("verifyUser", "geçersiz kullanıcı adı veya porala");
return false;
}


Only I need something ;

if($this->session->userdata('name')){
//show dashboard
}
else {
//show login
}


in the login page.

Answer

loginModel

public function login($name, $pass){
    $this->db->select("username", "password");
    $this->db->from("users");
    $this->db->where("username", $name);
    $this->db->where("password", $pass);
    $query = $this->db->get();
    $ret = $query->row();
    if($query->num_rows() == 1){
        //set the session data (you can add more values to array according to your needs)
            $data = array(
            'user_id' => $ret->user_id, //change your actual user id field
            );
        $this->session->set_userdata($data);
        //set the session data
        return true;
    }
    else {
        return false ;            
    }
}

To check

if($this->session->userdata('user_id')){
    //redirect to dashboard
}
else{
    //redirect to login
}

This will work properly. Change name of variables according to your needs.

Comments