-1

Possible Duplicate:
PHP: “Notice: Undefined variable” and “Notice: Undefined index”

I have a member.php page which contains this piece of code:

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

Now in the teacherlogin.php I use "include" to include the code from the member.php page. The problem I have is that if I open up the teacherlogin.php page, it gives me an undefined variable error stating: Notice: Undefined variable: username in ... on line 25

Why is it stating it is undefined because I have defined it in the member.php page?

Below is the code in the 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";

}

?>
Community
  • 1
  • 1
user1394925
  • 754
  • 9
  • 28
  • 51

4 Answers4

1

It is defined only into the if block.

$username = "";
if (isset($_SESSION['teacherusername'])) {
    $username = $_SESSION['teacherusername'];
}
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

$username is not defined or used anywhere.

Do the same as on the member.php at the top op the teacherlogin.php

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

  $username = $_SESSION['teacherusername']; 
}
Conrad Lotz
  • 8,200
  • 3
  • 23
  • 27
0
$username = null; // ad this line to member.php 
if (isset($_SESSION['teacherusername'])) {
   $username = $_SESSION['teacherusername'];
Kerem
  • 11,377
  • 5
  • 59
  • 58
0

The variable $username is only set by your member.php when the user is logged in. Try using if(isset($username)) instead of if($username) in your teacherlogin.php.

matthias.p
  • 1,514
  • 9
  • 11