PHP会话变量未被保存

时间:2016-03-05 21:55:36

标签: php mysql session login

因此,在'index.php'中,用户将其用户名和密码放入HTML输入中,并将其保存为“$ username”和“$ password”。然后PHP说:

<?php
$loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
$user = mysqli_fetch_array($loginquery);
session_start();
$_SESSION['username'] = $user['username'];
echo $_SESSION['username'];
?>

它回显'$ _SESSION ['用户名']'好吧但如果我转到'home.php'它实际上没有保存变量,它说'注意:未定义的变量:/ Applications / XAMPP中的_SESSION第24行的/xamppfiles/htdocs/tobyscott/home.php

这真让我烦恼!谢谢:))

2 个答案:

答案 0 :(得分:1)

你有session_start();在你的home.php声明 - 或者它在那里丢失?

答案 1 :(得分:0)

听起来你正在使用提交给自己的脚本。

添加条件以确保仅在获取/提交时提交表单处理逻辑:

if( !empty( $_POST[ 'varname' ] ) )
{
    // Logic
    $loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $user = mysqli_fetch_array($loginquery);
    session_start();
    $_SESSION['username'] = $user['username'];
    echo $_SESSION['username'];
}

OR:

if( !empty( $_GET[ 'varname' ] ) )
{
    // Logic
    $loginquery = mysqli_query($connection,"SELECT * FROM users WHERE username = '$username' AND password = '$password'");
    $user = mysqli_fetch_array($loginquery);
    session_start();
    $_SESSION['username'] = $user['username'];
    echo $_SESSION['username'];
}