为什么我不能在PHP中的多个文件中访问会话变量?

I have a login checker that redirects the user to a homepage if the check succeeds. I save the username in session variable at 'username' index.

<?php

ob_start();
include("db.php");
session_start();
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];


$sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
$result=pg_query($sql);

$count=pg_num_rows($result);

if($count==1){
$_SESSION['username'] = $myusername;
header("location:homepage.php");
}
else {
    echo "Wrong Username or Password";
}
ob_end_flush();
?>

I try to access the index but get an error that it doesn't exists

 <p>WELCOME!</p>
<?php
session_start();
echo $_SESSION['username'];

I call session_start in each file so I can't see the problem.

   Check  your $count variable's  value, 
   I think your  session is not creating due to your conditions.

   If your $count value will 1 then it will print session's value.

   Your code is fine, no need to change the code, only check your conditions.

   I am sure your issue will be solve.  

   Change
   if($count==1){
          $_SESSION['username'] = $myusername;
          header("location:homepage.php");
      } 
   To 

    if($count){
          $_SESSION['username'] = $myusername;
          header("location:homepage.php");
      } 

try this:

<?php
include("db.php");
session_start();
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

if($myusername!="" and $mypassword!="")
{
    $sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword'";
    $result=pg_query($sql);

    $count=pg_num_rows($result);

    if($count==1)
    {
        $_SESSION['username'] = $myusername;
        header("location:homepage.php");
    }
    else {
        echo "Wrong Username or Password";
    }
}else {
    echo "Please Enter Username and Password";
}
?>

what if some one enters ' or 1 or ' as password? do sanitize inputs.

As for the missing $_SESSION['username']

first check the value of $count to verify that the credentials are correct.

if that is fine check your browser. php sessions are based on a cookie value. check your if cookies are allowed in our browser.

if allowed look for a cookie named PHPSESSID, if its set and valid.

This way you should be able to pin point your problem.

this extension can help in inspecting cookie values in chrome.