doflamingo
doflamingo

Reputation: 565

PHP - How to validate multiple input with same name

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?

Upvotes: 2

Views: 1297

Answers (1)

Robbie
Robbie

Reputation: 17720

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

Upvotes: 1

Related Questions