PHP - 如何验证具有相同名称的多个输入

时间:2017-01-18 02:39:06

标签: php html

注意:不使用jquery或javascript验证

如何使用相同名称的多个输入进行验证?

<form action="" method="post"">
Product1 <input type="text" name="your_product[]"> <br>
Product2 <input type="text" name="your_product[]"> <br>
.....
Product N <input type="text" name="your_product[]">
<input type="submit"
</form>

PHP

if($_POST)
{
    $error = "";

   for($i=0; $i < count($_POST['your_product']); $i++)
   {
      if($_POST['your_product'][$i] == "")
      {
         $error = "Please fill your product";

      }
      else 
      {
          $_SESSION['product'][$i] = $_POST['your_product'][$i];
      }
   }
}

问题:如果用户填写第一个输入(但未填充第二个输入),则第一个值仍包含在session中。 如果他忘记填写下一个输入,我想停止第一次包含会话的过程。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

有两种选择:

1)只有在您知道没有错误时才更新会话;首先保存另一个变量的任何更新

 if($_POST) {
     $error = "";
     $aToUpdate = [];

     for($i=0; $i < count($_POST['your_product']); $i++) {
         if($_POST['your_product'][$i] == "") {
             $error = "Please fill your product";
         } else {
             $aToUpdate[$i] = $_POST['your_product'][$i];
         }
     }
     if (strlen($error) == 0) {
         $_SESSION['product'] = $aToUpdate;
     }
 }

2)首先进行两次验证(我的首选),然后在验证通过时进行处理

 if($_POST) {
     // Validate first
     $error = "";
     for($i=0; $i < count($_POST['your_product']); $i++) {
         if($_POST['your_product'][$i] == "") {
             $error = "Please fill your product";
         }
     }

     // If not errors, then update everything.
     if (strlen($error) == 0) {
         for($i=0; $i < count($_POST['your_product']); $i++) {
             $_SESSION['product'] = $_POST['your_product'][$i];
             }
         }
     }
 }