-1

可能重复:
PHP:“注意:未定义的变量”和“注意:未定义的索引”

我有一个包含这段代码的 member.php 页面:

<?php
    if (isset($_SESSION['teacherusername'])) 
    {
        $username = $_SESSION['teacherusername'];
    }
?>

现在在teacherlogin.php 中,我使用“include”来包含member.php 页面中的代码。我遇到的问题是,如果我打开teacherlogin.php 页面,它会给我一个未定义的变量错误,说明: Notice: Undefined variable: username in ... on line 25

为什么它说它是未定义的,因为我已经在 member.php 页面中定义了它?

以下是teacherlogin.php 中的代码:

<?php
  // PHP code
  session_start(); 

    ini_set('display_errors',1); 
 error_reporting(E_ALL);

// connect to the database
include('connect.php');
include('member.php');

  /* check connection */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
  }

  // required variables (make them explciit no need for foreach loop)
  $teacherusername = (isset($_POST['teacherusername'])) ? $_POST['teacherusername'] : '';
  $teacherpassword = (isset($_POST['teacherpassword'])) ? $_POST['teacherpassword'] : '';
  $loggedIn = false;
  $active = true;

  if ($username){
      echo "You are already Logged In: <b>{$_SESSION['teacherforename']} {$_SESSION['teachersurname']}</b> | <a href='./teacherlogout.php'>Logout</a>";
  }
  else{

echo "Please Login";

}

?>
4

4 回答 4

1

它仅在 if 块中定义。

$username = "";
if (isset($_SESSION['teacherusername'])) {
    $username = $_SESSION['teacherusername'];
}
于 2012-08-15T13:41:04.983 回答
0

$username没有在任何地方定义或使用。

与顶部 opteacherlogin.php 的 member.php 执行相同操作

if (isset($_SESSION['teacherusername'])) {

  $username = $_SESSION['teacherusername']; 
}
于 2012-08-15T13:40:53.523 回答
0
$username = null; // ad this line to member.php 
if (isset($_SESSION['teacherusername'])) {
   $username = $_SESSION['teacherusername'];
于 2012-08-15T13:41:12.923 回答
0

该变量$username仅在用户登录时由您的 member.php 设置。尝试在您的teacherlogin.php 中使用if(isset($username))而不是if($username)

于 2012-08-15T13:41:56.643 回答