如何在会话中获取用户ID?

时间:2015-07-14 14:45:08

标签: php session

有点noob问题,但我正在研究它大约2个小时,我无法解决这个问题

我有一个工作正常的登录系统(感谢教程),但现在我想在用户登录时将ID保存在会话中

这是我的login.php:

<?php session_start();
require_once 'config.php';
if(isset($_POST['btn-login'])){
 $uname = $_POST['txt_uname_email'];
 $umail = $_POST['txt_uname_email'];
 $upass = $_POST['txt_password'];
 $sth = $bdd->prepare("SELECT user_id FROM users WHERE user_name=$uname");
 $sth->execute();
 $result = $sth->fetch(PDO::FETCH_ASSOC);
 $uid = $result;

 if($user->login($uname,$umail,$upass)){
            $_SESSION['user_name'] = $uname;
            $_SESSION['user_mail'] = $umail;
            $_SESSION['user_session'] = $userRow['user_id'];
            $_SESSION['user_id'] = $uid;
            $uname = $_POST['txt_uname_email'];


            $umail = $_POST['txt_uname_email'];
            $upass = $_POST['txt_password'];
            var_dump($_SESSION['user_name']);
            $user->redirect('index.php');
         } else {
            $error = "Wrong Details !";
         } 
   }
?>

$ _SESSION ['user_name']的var_dump有效,但当我执行var_dump($ _ SESSION ['user_id']);时,它显示“null”

我根本不知道问题是什么..有人得到了解决方案吗?

谢谢

1 个答案:

答案 0 :(得分:0)

这不是答案,而是指出正确的方向并突出显示代码中的错误,

<?php session_start();
require_once 'config.php';
if(isset($_POST['btn-login'])){
 $uname = $_POST['txt_uname_email']; //Here $_POST Same
 $umail = $_POST['txt_uname_email']; //Here $_POST Same
 $upass = $_POST['txt_password'];
 $sth = $bdd->prepare("SELECT user_id FROM users WHERE user_name=$uname");
 $sth->execute();
 $result = $sth->fetch(PDO::FETCH_ASSOC);
 $result = $_SESSION['user_id']; // What is this,?
 $uid = $result; // What is this?

 //You are not fetching any data from database against your SELECT query

 if($user->login($uname,$umail,$upass)){
    //Here you are setting POST variables as session, thats why you are getting $_SESSION['user_name'] on var_dump
            $_SESSION['user_name'] = $uname;
            $_SESSION['user_mail'] = $umail;
            $_SESSION['user_session'] = $userRow['user_id']; //Where is this coming from
            $_SESSION['user_id'] = $uid; //It can't be eqaul to $result;
            $uname = $_POST['txt_uname_email']; // Mistake
            $umail = $_POST['txt_uname_email']; // Mistake
            $upass = $_POST['txt_password']; // Mistake
            var_dump($_SESSION['user_name']);
            $user->redirect('index.php');
         } else {
            $error = "Wrong Details !";
         } 
   }
?>