Printing a PHP error inline instead of erasing the

2019-02-21 04:23发布

问题:

How can I make PHP print an error inline instead of changing the entire page?

I'd like it to target #errors and fill that instead of changing everything.

The code I'm currently using is die ("Incorrect username or password.");

I'm very new to PHP so sorry if this is a pretty easy thing to do.

回答1:

Put the error in a variable where you do your logic and print its contents in #errors. For example:

if (username_is_incorrect()) $error = 'Incorrect username or password.';

And in the HTML

<?php if (isset($error)):?><div id="errors"><?=$error?></div><?php endif;?>


回答2:

There are 2 ways of doing it.

A real inline method is not entirely PHP-based, as it cannot be used without JavaScript and AJAX calls.
Note the irritating disadvantage of this method: you will need to re-check every field again upon receiving form data finally.

Another one will reload your page but it will be the same page with all the form fields, entered data and also freshly generated error messages. This is called POST/Redirect/GET pattern

here is a short example

<?  
if ($_SERVER['REQUEST_METHOD']=='POST') {  

  $err = array();
  //performing all validations and raising corresponding errors
  if (empty($_POST['name']) $err[] = "Username field is required";  
  if (empty($_POST['text']) $err[] = "Comments field is required";  

  if (!$err) {  
    // if no errors - saving data 
    // and then redirect:
    header("Location: ".$_SERVER['PHP_SELF']);
    exit;
  }  else {
    // all field values should be escaped according to HTML standard
    foreach ($_POST as $key => $val) {
      $form[$key] = htmlspecialchars($val);
    }
} else {
  $form['name'] = $form['comments'] = '';  
}
include 'form.tpl.php';
?>  

while in the form.tpl.php file you have your form fields, entered values and conditional output of error messages

<? if ($err): ?>
  <? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
  <? endforeach ?>
<? endif ?>
<form>
  <input type="text" name="name" value="<?=$form['name']?>">
  <textarea name="comments"><?=$form['comments']?></textarea>
  <input type="submit">
</form>