验证表单并使用相同的参数保持在同一页面上

时间:2018-03-28 09:36:37

标签: php validation

所以我想验证一些表单字段,如果有错误,它们应该显示在包含参数的相同网址的同一页面中,它会对它们进行验证,但是当它重定向到同一页面时,URL会丢失它&#39 ; s参数并没有显示它需要的东西,我得到id_carte = 2 $id_carte = $_GET['id_carte'];

哪个螺钉与该页面上显示的内容

<form class="carte-coment-box" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
    <input class="coment-box-input" type="text" name="nume_utilizator" placeholder="Nume">
    <input class="coment-box-input" type="email" name="adresa_email" placeholder="Email">

    <span class="width50 error"><?php echo $nameErr;?></span>
    <span class="width50 error"><?php echo $emailErr;?></span>

    <textarea class="width100 coment-box-textarea" name="comentariu" cols="45" placeholder="Adauga opinia ta despre carte" maxlength="1000"></textarea>
    <span class="width100 error"><?php echo $comentErr;?></span>

    <input type="hidden" name="id_carte" value="<?=$id_carte?>">
    <input class="btn btn-primary coment-box-btn" type="submit" value="Adauga">   
</form>

这是验证

$name = $email  = $comment = "";
$nameErr = $emailErr = $comentErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (empty($_POST["nume_utilizator"])) {
    $nameErr = "*Numele este necesar";
  } else {
    $name = test_input($_POST["nume_utilizator"]);
  }

  if (empty($_POST["adresa_email"])) {
    $emailErr = "*Emailul este necesar";
  } else {
    $email = test_input($_POST["adresa_email"]);
  }

  if (empty($_POST["comentariu"])) {
    $comentErr = "*Campul nu poate fi gol";
  } else {
    $comment = test_input($_POST["comentariu"]);
  }  
}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

我想要的结果是

  if($nameErr === '' && $emailErr === '' && $comentErr === ''){
    //run adauga_comentariu.php as if it was in <form class="carte-coment-box" action="adauga_comentariu.php" method="POST">

  } else {
    //don't change URL, errors already are displayed as they should, ONLY problem is that the URL takes out the id_carte=2 which is necessary for rendering what it needs
  }

0 个答案:

没有答案