how to stop my php page from continuing when field is empty

冷暖自知 提交于 2019-12-25 02:15:43

问题


<?php 
if(isset($_POST['submit'])){ 
echo "wht the heck"; 
$avail = new CheckEmptyFields(); 
$avail->availtime=$_POST['available_time']; 
echo $avail->chkFieldAvailableTime(); 
} 
else { 
print "<font color='red'>*</font>Printing else"; 
} 
?>

in my page but when i press continue the page goes on next page while field is empty.

beacuse i see "printing else" on the page even b4 i press continue so the script ran before while it should run when the user presses continue button.


回答1:


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
   if (isset($_POST['submit'])) {
      ... yada yada yada ...
   } else {
      echo '<font yada yada yada';
   }
}

With this, the isset will ONLY be checked if the page was actually requested via a POST hit. If it's loaded via GET or any other method, that chunk of code simply won't execute at all.




回答2:


The else statement is executed if $_POST['submit'] is not set. On page load (before user clicks submit), that is the case.

Edit: Now that I think about it, did you put the two in different pages? What's form's action attribute?




回答3:


try replacing the isset() with !empty(), it could be happening due to $_POST['submit'] being SET, but having no value. empty() returns true for, as the name describes, any type that is empty, see: http://php.net/manual/en/function.empty.php

So basically isset() will return false only if the variable is not set, but !empty() will return false even if the variable is set but considered empty (set to FALSE, NULL, 0 .etc). Give it a try.



来源:https://stackoverflow.com/questions/5901138/how-to-stop-my-php-page-from-continuing-when-field-is-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!