user3912595
user3912595

Reputation: 1

How to pass error using session

How to pass this error to the next page using session. I tried passing it but it always get the last error. Why?

$err = "You forgot to enter you password";
$err  = "Your forgot to enter you username";
$err = "You forgot to enter you telephone number";

I try pass this one like this. With this one it give me the last error. Why is it? I added also a session start above this two pages.

Page1. php
$_SESSION['errMsg'] = $err;

page2.php 
$getError = $_SESSION['errMsg'];
echo $getError;

Upvotes: 0

Views: 980

Answers (3)

Darren
Darren

Reputation: 13128

It always gets the "last error" because the way you set it:

$err = "You forgot to enter you password";
$err  = "Your forgot to enter you username";
$err = "You forgot to enter you telephone number";

Means that the last line will always be the error message because you over-write the $err variable.

Simply throw in a condition:

if(THIS ERROR) {
    $err = "You forgot to enter you password";
} else if(THAT ERROR) {
    $err = "You forgot to enter you telephone number";
} else {
    $err to: "You forgot to enter you telephone number";
}

Or a simple switch/case

switch($error) {
    case 'mobile';
         $err = "You forgot to enter you password";
         break;
    ///.....etc
}

Upvotes: 0

John Conde
John Conde

Reputation: 219924

You're overwriting your $err variable each time you add an error. You need to concatenate or make an array of errors to pass to the next page.

$err .= "You forgot to enter you password";
$err .= " Your forgot to enter you username";
$err .= " You forgot to enter you telephone number";

$_SESSION['errMsg'] = $err;

page2.php 
$getError = $_SESSION['errMsg'];
echo $getError;

or

$err = array(
    "You forgot to enter you password",
    "Your forgot to enter you username",
    "You forgot to enter you telephone number"
);
$_SESSION['errMsg'] = $err;

page2.php 
$getError = implode(' ', $_SESSION['errMsg']);
echo $getError;

These examples are very basic but should show you how to solve your problem.

Upvotes: 2

Anonymous Penguin
Anonymous Penguin

Reputation: 2137

You always get the last message? That is because that is the last value you gave your variable! You're always going to get the last one there.

If you need to control it, use an if statement:

if(condition==true) {
  $err = "You forgot to enter you password";
} else {
  $err = "You forgot to enter you telephone number";
}

You go:

Create $err with the value: "You forgot to enter you password";
Update $err to: "Your forgot to enter you username";
Update $err to: "You forgot to enter you telephone number";

Whenever you reference $err, you are getting the most recent value.

What you probably want to do is this:

$err = "First condition";
$err = $err . " " . "Second Condition";

That would have $err be First condition Second Condition.

Upvotes: 0

Related Questions