如何使用会话传递错误

时间:2014-08-07 01:19:53

标签: php session error-handling

如何使用会话将此错误传递到下一页。我尝试传递它,但它总是得到最后一个错误。为什么呢?

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

我试着像这样传递这个。有了这个,它给了我最后一个错误。为什么?我在这两页之上添加了一个会话开始。

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

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

3 个答案:

答案 0 :(得分:2)

每次添加错误时,您都会覆盖$ err变量。您需要连接或生成一组错误才能传递到下一页。

$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;

$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;

这些示例非常基本但应该向您展示如何解决您的问题。

答案 1 :(得分:0)

你总是收到最后一条消息?那是因为那是你赋予变量的最后一个值!你总是会在那里得到最后一个。

如果需要控制它,请使用if语句:

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

你去:

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";

每当您引用$err时,您都会获得最新值。

您可能想要做的是:

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

这将$errFirst condition Second Condition

答案 2 :(得分:0)

它总是得到"最后一个错误"因为你设置它的方式:

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

意味着最后行将始终成为错误消息,因为您覆盖 $err变量。

简单地说:

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";
}

或简单的switch/case

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