会话没有被宣布

时间:2017-05-03 17:54:08

标签: php session session-variables

这是我的登录代码

global $connection;

if (isset($_POST['user_login'])) {

    $email = $_POST['email'];
    $password = $_POST['password'];
    $password= md5($password);

    $login = mysqli_query($connection, "SELECT * FROM user WHERE email ='{$email}' AND password = '{$password}' ");
    if(!$login) {
        die("QUERY FAILED" . mysqli_error($connection));
    }

    if(!$login || mysqli_num_rows($login) == 0) {

        echo "<div class='alert alert-danger' role='alert'> <strong>Your Username or Password is invalid!</strong></div>";

    } else {
        $_SESSION['user_id'] = $user_id;
        $_SESSION['email'] = $email;
        $_SESSION['username'] = $username;

        header('Location: index.php');
    }
}

我使用print_r函数显示所有会话,但只声明了会话电子邮件。为什么user_id和username没有被声明?我做错了什么?

2 个答案:

答案 0 :(得分:0)

  1. 您可能忘记在顶部声明session_start();
  2. 您的会话中似乎使用的是user_idusername,但它们并非来自PHP代码中的任何位置。因此,您可能会忘记从$login响应中获取然后使用它们。
  3.   

    这是一个假设,因为您的代码看起来使用user_id和   基于username查询的SELECT

    因此,您可以尝试使用此代码,该代码包含从select query中使用的所有参数:

    session_start();
    global $connection;
    
    if (isset($_POST['user_login'])) {
    
        $email = $_POST['email'];
        $password = $_POST['password'];
        $password= md5($password);
    
        $login = mysqli_query($connection, "SELECT * FROM user WHERE email ='{$email}' AND password = '{$password}' LIMIT 1");
        if(!$login) {
            die("QUERY FAILED" . mysqli_error($connection));
        }
    
        if(!$login || mysqli_num_rows($login) == 0) {
    
            echo "<div class='alert alert-danger' role='alert'> <strong>Your Username or Password is invalid!</strong></div>";
    
        } else {
            // get user_id and username fetched from your Select query
            while($row = $login->fetch_assoc()) {
              $_SESSION['user_id'] = $row['user_id']; // assuming user_id as a column
              $_SESSION['email'] = $email;
              $_SESSION['username'] = $row['username']; // assuming username as a column
            }
            header('Location: index.php');
        }
    }
    

答案 1 :(得分:-1)

当您尝试将未初始化的变量或空值放入会话时,会话不会引发异常。但是键和值列表,不能添加不是init变量或null值。