ahmedsaber111
ahmedsaber111

Reputation: 822

how to return the user id when the user logged in successfully in codeigniter

here is the controller to login form, after the login process the user will be able to do add posts to database, so i need to collect some data as the username of the current logged user & the id of this user in the {users table}

<?php

class login extends CI_Controller{
function index()
{
    $this->load->view('login_form');
}
function proccess()
{
    $this->load->model('membership_model');
    $query = $this->membership_model->validate();

    if($query) // if the user's credentials validated ..
    {
        $data = array(
            'username_usr' => $this->input->post('username'),
            'is_logged_in' => true
        );
        $this->session->set_userdata($data);

        redirect('view=dogo&do=new_post');
    }
    else 
    {
        $this->index();
    }
}

function signup()
{
    //signup proccess
}
}

and here is the model of login process

<?php
class Membership_model extends CI_Model{
function validate()
{
    $this->db->where('username_usr', $this->input->post('username'));
    $this->db->where('password_usr', md5($this->input->post('password')));
    $query = $this->db->get('hs_users_usr');

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

I can return the username of the logged user, i need also to return the id of this user

Upvotes: 0

Views: 193

Answers (1)

michaeljdennis
michaeljdennis

Reputation: 612

You can return the query if it's successful and pull the user id from it:

Controller

<?php

class login extends CI_Controller{
function index()
{
    $this->load->view('login_form');
}
function proccess()
{
    $this->load->model('membership_model');
    $query = $this->membership_model->validate();

    if($query !== FALSE) // if the user's credentials validated ..
    {
        $user_data = $query->row();

        $data = array(
            'user_id' => $user_data->id,
            'username_usr' => $this->input->post('username'),
            'is_logged_in' => true
        );

        $this->session->set_userdata($data);

        redirect('view=dogo&do=new_post');
    }
    else 
    {
        $this->index();
    }
}

function signup()
{
    //signup proccess
}
}

Model

<?php
class Membership_model extends CI_Model{
function validate()
{
    $this->db->where('username_usr', $this->input->post('username'));
    $this->db->where('password_usr', md5($this->input->post('password')));
    $query = $this->db->get('hs_users_usr');

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

Upvotes: 1

Related Questions