Php 会话错误未定义索引

Php session error undefined index

session_start();

if (isset($_POST['username'] , $_POST['password'])) {

    $extractabout = $db->prepare("SELECT * FROM user WHERE username = :username && password = :password");

    $extractabout->execute([
        'username' => $_POST['username'],
        'password' => $_POST['password']
    ]);

    $infos = $extractabout->rowCount() ? $extractabout : [] ;

    foreach ($infos as $info) {
        if(!empty($info['username']) && !empty($info['password']) && !empty($info['id']) && !empty('role')) {
            $_SESSION['username'] == $info['username'];
            $_SESSION['password'] == $info['password'];         
        }

    }

    if(isset($_SESSION['username'], $_SESSION['password'], $_SESSION['user_id'], $_SESSION['role'])) {
        header("Location: test.php");
    }   

}

?>

当我给 $_SESSION['username'] 一个名为 $info['username'] 的值时出错:

Undefined index: username
Undifined index: password

你不需要分配值,你只需要使用一个 = 所以使用这个:

$_SESSION['username'] = $info['username'];
$_SESSION['password'] = $info['password']; 

另外,我会在每个 header 之后放一个 exit();,这样您就可以确定脚本停止执行了!

header("Location: test.php");
exit();

使用 = 在会话中分配值而不是 ==(比较)。

还有什么是 !empty('role') 我想应该是 !empty($info['role'])

if(!empty($info['username']) && !empty($info['password']) && !empty($info['id']) && !empty($info['role'])) {
        $_SESSION['username'] = $info['username'];
        $_SESSION['password'] = $info['password'];                     
}

您的代码中存在语法错误,更正的错误是:

if(!empty($info['username']) && !empty($info['password']) && !empty($info['id']) && !empty($info['role'])) {
    $_SESSION['username'] = $info['username'];
    $_SESSION['password'] = $info['password']; 
}