Adding user id from database to session data in Codeigniter?

I am new to CodeIgniter and am facing problem while adding user id (after user login) from database to session data, here my question with code may have been asked earlier in SOF, after all my efforts asking about it

// Login model

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login_model extends CI_Model
{
     function __construct()
     {
          // Call the Model constructor
          parent::__construct();

     }

     //get the username & password from tbl_usrs
     public function get_user($usr, $pwd)
     {    
          $sql = "select * from tbl_usrs where username = '" . $usr . "' and password = '" .$pwd . "' ";
          $query = $this->db->query($sql);
          return $query->num_rows();
     }

/*           public function set_session($username) {
                $sql="SELECT * FROM tbl_usrs WHERE username='".$username."' LIMIT 1 ";
                $result=$this->db->query($sql);
                $row=$result->row();


                $sess_data=array (

                    'id'=>$row->id,
                    'username'=>$username,
                    'is_login'=>TRUE
                    );

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




            } //set_seesion function ends
*/   
    }

?>

      

// login controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
print_r( debug_backtrace() );
//ini_set('memory_limit', '-1');
//ini_set('max_execution_time', 3000);
ini_set('display_errors',1);
error_reporting(E_ALL);
class LoginController extends CI_Controller
{

     public function __construct()
     {
          parent::__construct();
          $this->load->library('session');
          $this->load->helper('form');
          $this->load->helper('url');
          $this->load->helper('html');
          $this->load->database();
          $this->load->library('form_validation');

     }

     public function index()
     {
            //load the login model
          $this->load->model('login_model');
        //  $qry=$this->login_model->validate();



          //get the posted values
          $username = $this->input->post("username");
          $password = $this->input->post("password");
          $user_id = $this->input->get("user_id");

          //set validations
          $this->form_validation->set_rules("username", "username", "trim|required");
          $this->form_validation->set_rules("password", "password", "trim|required");

          if ($this->form_validation->run() == FALSE)
          {
               //validation fails
               redirect('Homecontroller/index');  //make new controller for loading a form again
               echo "Validation fails"; // even for no name and passwrd
          }
          else
          {
               //validation succeeds
               if ($this->input->post('submit') == "Login")
               {
                    //check if username and password is correct
                    $usr_result = $this->login_model->get_user($username, $password);
                    if ($usr_result > 0) //active user record is present
                    {
                         //set the session variables
                         $sessiondata = array(
                              'user_id' => $user_id,
                              'username' => $username,
                              'password'=>$password,
                              'is_login' => TRUE
                         );
                         //$this->login_model->set_session($username);
                         $this->session->set_userdata($sessiondata);
                         print_r($this->session->all_userdata());  //to check
                         redirect(base_url("Site/member_area"));
                         return  $username;
                    }
                    else
                    {
                         $this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
                         redirect('Homecontroller/index');
                    }
               }
               else
               {
                    redirect('login/home3');
               }
          }
     }


}?>

      

when i try to print session data i get user_id => empty

+3


source to share


1 answer


None of these variables will be available for you to assign:

'user_id' => $user_id,
'username' => $username,
'password'=>$password,

      

The reason for this is because you used:

$usr_result = $this->login_model->get_user($username, $password);

      

However, this will only be the result of the number of rows returned:

public function get_user($usr, $pwd)
...
    return $query->num_rows();

      



So now $usr_result

will be the number of rows returned, not the data of the corresponding user.

So what you need to do is set the session data in this login function above return $query->num_rows();

and below instead $query=

.

public function get_user($usr, $pwd){
    ....
    $query = $this->db->query($sql);
    $this->session->set_userdata('sessiondata', $query->row_array());
}

      

Note that since we are only fetching 1 user from our request, we would also like to only return 1 row back. Also, you want to store an associative array, not an object, so we use $query->row_array()

to return 1 row

in a format array

where key

is the column name and value is the result column.

Now do echo '<pre>', print_r($this->session->userdata('sessiondata'), true),'</pre>';

to get a formatted list of this object that contains an array. Then you can display the names appropriately.

Sidenote, I would not store the password in the session.

0


source







All Articles