2

Note: Without using jquery or javascript validate

How to validate with multiple input with same name?

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

Problem: If user fill the first input(but not fill the second input), the first value still contain to session. I want to stop the process for first contain session if he forgot fill in the next input. How could I do?

2
  • use break to exit the for loop on the first error Commented Jan 18, 2017 at 2:56
  • @nogad The session will still contain the first value. So this is not the desired output. Commented Jan 18, 2017 at 3:20

1 Answer 1

1

There are two options:

1) Only update the session when you know there are no errors; hold any updates in another variable first

 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) Do in two passes (my preferred) of validate first, then process if validation passes

 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];
             }
         }
     }
 }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.