将数据库中的用户ID添加到Codeigniter中的会话数据中? [英] adding user id from database to session data in Codeigniter?

查看:95
本文介绍了将数据库中的用户ID添加到Codeigniter中的会话数据中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新的CodeIgniter和面临问题,在添加用户ID(用户登录后)从数据库到会话数据这里是我的代码问题可能会问之前的SOF,在我把所有的努力,我问这个

// login-model

 <?php if ('BASEPATH'))exit('不允许直接脚本访问); 

类Login_model extends CI_Model
{
function __construct()
{
//调用Model构造函数
parent :: __ construct ;

}

//获取用户名& password from tbl_usrs
public function get_user($ usr,$ pwd)
{
$ sql =select * from tbl_usrs where username ='。 $ usr。 '和password ='。$ pwd。 ';
$ query = $ this-> db-> query($ sql);
return $ query-> num_rows();
}

/ * public function set_session($ username){
$ sql =SELECT * FROM tbl_usrs WHERE username ='。
$ 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函数结束
* /
}


//登录控制器

 <?php if(!defined('BASEPATH'))exit('不允许直接脚本访问); 
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()
{
//加载登录模型
$ this-> load-> model('login_model');
// $ qry = $ this-> login_model-> validate();



//获取发布的值
$ username = $ this-> input-> post(username);
$ password = $ this-> input-> post(password);
$ user_id = $ this-> input-> get(user_id);

//设置验证
$ this-> form_validation-> set_rules(username,username,trim | required);
$ this-> form_validation-> set_rules(password,password,trim | required);

if($ this-> form_validation-> run()== FALSE)
{
//验证失败
redirect('Homecontroller / index' ); // make new controller for load a form again
echo验证失败; //即使没有名字和passwrd
}
else
{
//验证成功
if($ this-> input-> post ')==Login)
{
//检查用户名和密码是否正确
$ usr_result = $ this-> login_model-> get_user($ username,$ password) ;
if($ usr_result> 0)//活动用户记录存在
{
//设置会话变量
$ 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()); //检查
redirect(base_url(Site / member_area));
return $ username;
}
else
{
$ this-> session-> set_flashdata('msg','< div class =alert alert-danger text-center> ;用户名和密码无效!< / div>');
redirect('Homecontroller / index');
}
}
else
{
redirect('login / home3');
}
}
}


}?>

当我尝试打印会话数据视图中我得到user_id =>空

解决方案

这些变量不会用于您的分配:

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

您已使用:

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

但是,这只会是返回的行数的结果:

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

现在, $ usr_result



因此,您应该做的是将该登录函数中的会话数据设置为 return $ query-> num_rows(); 以及 $ query =

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

请注意,由于我们只从我们的查询中检索1个用户,只有想得到1行回。此外,你想要存储一个关联数组,而不是一个对象,所以我们使用 $ query-> row_array()返回 1行格式化为数组其中是列名称,



现在,执行 echo'< pre>',print_r($ this-> session-> userdata 'sessiondata'),true),'< / pre>'; 来获得包含数组的对象的格式化列表。



Sidenote,我不会在会话中存储密码。


i am new to CodeIgniter and facing problem in adding user id(after user has logged in) from database to session data here is my code question may be asked before on SOF , after putting all my efforts i am asking this

//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 am try to print session data in view i am getting user_id=> empty

解决方案

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

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

The reason for this is that you've used:

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

However, that is only going to 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 user in question.

So, what you should do, is instead set the session data in that login function above return $query->num_rows(); and below $query=.

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

Note that as we only retrieve 1 user from our query ever, we also would only ever want to get 1 row back. Furthermore, you're wanting to store an associative array, and not an object, so we use $query->row_array() to get back 1 row formatted as an array where the key is the column name and the value is the columns result.

Now, do a echo '<pre>', print_r($this->session->userdata('sessiondata'), true),'</pre>'; to get a formatted list of that object which contains the array. Then you can map names accordingly.

Sidenote, i would not store the password in an session.

这篇关于将数据库中的用户ID添加到Codeigniter中的会话数据中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆