Dario
Dario

Reputation: 145

How to Check $_POST Variables for NULL dynamically

How to loop through $_POST variables sent by a form to make sure none of them are empty or NULL. For example, if a form has 15 fields and is submitted. How to check that each of those 15 fields actually contained something other than NULL. I have multiple Forms but one validator class so I cannot specify the variable in the post array that need to be checked for each form.

I tried using foreach but that seemed to clear the $_POST array or corrupt it for some reason? The not working code is given below. If I var_dump($_POST) before I use the foreach and after the foreach I get an empty array after, but the correct values before. So I thing foreach is out of the question. Any Ideas?

foreach($_POST as $key => $value)
{
if ($value==NULL)
header ("Location: index.php")
}

Upvotes: 0

Views: 2235

Answers (4)

Dario
Dario

Reputation: 145

The code given by littlibex worked Thank

foreach ($_POST as $key => $value) {
if ($value === '')
    header("Location: index.php");
}

I only used two equal signs though.

Upvotes: 0

littleibex
littleibex

Reputation: 1712

You will not get any NULL values in $_POST array. If the form is submitted successfully and if the HTML form was not tampered with then all the fields will at least have some value or they will be empty ''. Do not use empty() function of PHP because it even considers 0 and a few other values as empty which might actually be the value. I believe this would be the correct way to write your code:

foreach ($_POST as $key => $value) {
    if ($value === '')
        header("Location: index.php");
}

Upvotes: 2

hamed
hamed

Reputation: 8033

You can do this:

foreach($_POST as $key => $value)
{
   $valid = 15;
   if(empty($value))
     $valid --;

   if($valid == 15)
    {
     //validation ok
    }

   else  //This means at least one of the 15 fields is empty
     header ("Location: index.php")
}

Second solution: It's better to use array in your view, for example

<input type="text" name="Form[name]" />
<input type="text" name="Form[family]" />
... 
<input type="text" name="Form[address]" />

In this case, $_POST['Form'] is an array and you can access it's elements. For example $_POST['Form']['name'] equal to value of first textbox. So your foreach should be like this:

foreach($_POST['Form'] as $key => $value)
...

Upvotes: 0

Manoj Dhiman
Manoj Dhiman

Reputation: 5166

try this

 foreach($_POST as $key => $value)
    {
    if (empty($value))
    header ("Location: index.php")
    }

Upvotes: 0

Related Questions