basiclearner
basiclearner

Reputation: 49

Session variable not stored on other pages

i am using session variable to send details of user from login page to welcome page .

here is my code :

<?php   

 if(isset($_POST['login']))
 {



 $email=$_POST['email'];
 $pass=md5($_POST['password']);


 $a="SELECT * FROM users WHERE email='$email'AND password='$pass'";
 $log=mysqli_query($con,$a);
$row=mysqli_fetch_array($log);


if(mysqli_num_rows($log)>0){

 $_SESSION['firstname']=$row['first_name'];
$_SESSION['lastname']=$row['last_name'];


header("location:welcome.php");
exit;
}
else{

$er="login failed!";

 }
}

on Welcome.php

 <h2>WELCOME : <?php echo $_SESSION['firstname'];?></h2>  <--- line 63-->

but i am getting this error :

Notice: Undefined index: firstname in C:\xampp\htdocs\website\welcome.php on line 63

PS : kindly dont mark it as duplicate I tried many solutions but not helping. I used session_start(); on every page .

Upvotes: 2

Views: 66

Answers (2)

jasinth premkumar
jasinth premkumar

Reputation: 1413

A session is started with the session_start() function.

in 1st page:

if(mysqli_num_rows($log)>0){


    $row=mysqli_fetch_array($log);
    session_start();
    $_SESSION['firstname']=$row['first_name'];
    $_SESSION['lastname']=$row['last_name'];

    if(isset($_SESSION['firstname']))  
        header("location:welcome.php");
    exit;
}

on page 2:you might have write this line at 1st line:

<?PHP 
  session_start();
 ?>
 <h2>WELCOME : <?php if(isset($_SESSION['firstname']))  {echo $_SESSION['firstname'];}?></h2> 

Upvotes: 1

kscherrer
kscherrer

Reputation: 5766

Edit: this answer is not correct and I will remove it when the comment-discussion has ended.

You fetch the first row of $log and then AFTER that check if the number of rows in $log is bigger than 0. Although you had one row initially, you fetched it! so at the time you check mysqli_num_rows($log) it will be 0, therefore never setting $_SESSION['firstname'] and $_SESSION['lastname'].

Try checking for number-of-entries before fetching the row like this:

$a="SELECT * FROM users WHERE email='$email'AND password='$pass'";
$log=mysqli_query($con,$a);

if(mysqli_num_rows($log)>0){


    $row=mysqli_fetch_array($log);

    $_SESSION['firstname']=$row['first_name'];
    $_SESSION['lastname']=$row['last_name'];


    header("location:welcome.php");
    exit;
}

Upvotes: 0

Related Questions