开发者

PHP error displaying position.

I have following PHP code:

            if($_SESSION['msg']['login-err'])
            {
                echo '<p class="error">'.$_SESSION['msg']['login-err'].'</p>';
                unset($_SESSION['msg']['login-err']);
            }

Everything working fine开发者_Go百科. 'P' with error is displayed correctly inside element.

My question is how to specify where my error should be displayed?

E.G. Not as the first element inside the form, but

  • as the second for example
  • just before <input name="user" />

??

Any suggestion much appreciated.


Since you're (somewhat naively) testing for errors and displaying errors at the same time, you should just move the code lower in the page so that the test/output happen where you want it to display.

Ideally you should decouple your display code from your logic. Store your errors for later display in an $errors variable which is passed to your template to be rendered.


Rather than placing the echo where it exist now, why not change your code to something like this:

$error;
if($_SESSION['msg']['login-err'])
{
    $error = $_SESSION['msg']['login-err'];
    unset($_SESSION['msg']['login-err']);
}

Then, right above your input tag, do something like this...

<?php echo $error;?>

It's not the best way to do error handling...but it should do what you are asking.


The "where" depends on you frontend design.

In a login form I would recommend to display errors at the top or bottom of the whole form. In a contact/registration form it makes more sense to show error beside the field ( on the top or left ).

Quite different thing is this combination of logic and presentations. They should be separated, because each piece of code should have only one reason to change. Your piece has two reasons: design or logic.

You would gain a lot if you did some extended studies in MVC and OOP in general.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜