想要在其他页面中获取会话变量,但它没有显示.我能做什么


Want to get Session Variable in other page but its not showing up. What can I do?

我在functions.php文件中添加了这几行代码

 public function login(){
    $sql = "SELECT `ID`,`userName` FROM `userdata` WHERE `userName`=:userN AND `password`=:passd";
    $stmt = $this->pdo->prepare($sql);
    $stmt -> bindValue(":userN",$this->userName);
    $stmt ->bindValue(":passd",$this->password);
    $stmt ->execute();
    $userData = $stmt ->fetch();
    $check = $stmt ->rowCount();
    if($check==1){
        session_start();
        $_SESSION['login'] = true;
        $_SESSION['uid']   = $userData['ID'];
        $_SESSION['uName']   = $userData['userName'];
        $_SESSION['Name']   = $userData['Name'];
        $_SESSION['login_msg'] = "Login Successful";
        return true;
    }else{
        return false;
    }
}
public function getSession(){
    return @$_SESSION['login'];
}

在我的index.php文件中,我想获得需要来自mysql数据库的名称。

    session_start();
include_once "functions.php";
$object = new functions();
$userName   = $_SESSION['uName'];
$Name       = $_SESSION['Name'];
if(!$object->getSession()){
    header("Location: login.php");
    exit();
} 
echo "Welcome". $Name;

但这并没有显示在index.php页面上。怎么了?

试试这个

session_start();
public function login(){
   $sql = "SELECT `ID`,`userName` FROM `userdata` WHERE `userName`=:userN AND `password`=:passd";
   $stmt = $this->pdo->prepare($sql);
   $stmt -> bindValue(":userN",$this->userName);
   $stmt ->bindValue(":passd",$this->password);
   $stmt ->execute();
   $userData = $stmt ->fetch();
   $check = $stmt ->rowCount();
   if($check==1){
      $_SESSION['login'] = true;
      $_SESSION['uid']   = $userData['ID'];
      $_SESSION['uName']   = $userData['userName'];
      $_SESSION['Name']   = $userData['Name'];
      $_SESSION['login_msg'] = "Login Successful";
      return true;
   }else{
      return false;
   }
}

您甚至不必使用函数来获取会话。您可以随时随地使用$_SESSION['login']。但是,请确保在要使用会话的所有文件中都包含functions.php。