开发者

php checking if form was submitting with null field

开发者 https://www.devze.com 2023-04-07 18:14 出处:网络
As the title says, I\'m trying to figure out how to check if there were any null entries in a form after the submit button has been clicked.

As the title says, I'm trying to figure out how to check if there were any null entries in a form after the submit button has been clicked.

if(isset($_POST['submit']) && ($selected == ''|| $text == '' || $email == ''))
{
  // *do things*
}
else{
  //*more things*
}

is this 开发者_运维百科incorrect?


You would reference them in the same way that you handled the submit button.

That is: $_POST['input_name']

From there check it using the appropriate function: isset(), empty(), is_null() (although form variables rarely come across as null)

I'd also encourage you to read up on PHP external variables.


What you could do is to loop over the $_POST variables. Exclude those in which you're not interested in, and make something like:

$allIsOk = true;
foreach ($_POST as $index => $value) {
  if (strlen($value)<1) {
    $allIsOk = false;      
  }
}

...and then you make your choice on $allIsOk.

This approach is for two reasons:

  1. With suggestion above, you need to combine checks, since empty() will return true for 0 or even "0" and might cause headbanging problems.
  2. With this approach you can add parameters, without making a huge if statement

Of course, this is just the idea. It's always wise to check documentation. Also, you could substitute the foreach cycle with an array_walk invocation to make things fancier (esp. from PHP 5.3 onwards). ;-)

Good luck!

PS Also, to find out whether your script has been invoked by a POST action, instead of taking into account the submit element, I suggest you to use the $_SERVER global. http://php.net/manual/en/reserved.variables.server.php Just check for the 'REQUEST_METHOD' parameter.

So, you might have:

if ('POST' == $_SERVER['REQUEST_METHOD']) {

  // It's ok for these to be null - or empty
  $exclude = array('submit', 'other_param');
  $allIsOk = true;
  foreach ($_POST as $index => $value) {
    if (!in_array($index, $exclude) && strlen($value)<1) {
      $allIsOk = false;      
    }
  }
}

if ($allIsOk) {
  // Do Something
} else {
  // Do Something Else
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号