为什么我在提交按钮之前得到结果?

时间:2014-04-15 18:18:03

标签: php

我试图运行这个小块代码,但是我收到了消息"请检查所有字段"甚至在点击提交按钮之前。为什么会这样?我需要清除缓存吗?

<form name="frm1" action="index3.php" method="POST">
question 1:<br>
<input type="radio" name="q1" value="1" /> Answer 1<br>
<input type="radio" name="q1" value="2" /> Answer 2<br>
<input type="radio" name="q1" value="3" /> Answer 3<br><br>
question 2:<br>
<input type="radio" name="q2" value="1" /> Answer 1<br>
<input type="radio" name="q2" value="2" /> Answer 2<br>
<input type="radio" name="q2" value="3" /> Answer 3<br><br>
question 3:<br>
<input type="radio" name="q3" value="1" /> Answer 1<br>
<input type="radio" name="q3" value="2" /> Answer 2<br>
<input type="radio" name="q3" value="3" /> Answer 3<br> <br>
<br>
<input type="submit" name="btnSubmit" value="Submit Form" />
</form>

<?php
if(isset($_POST['q1']) && isset($_POST['q2']) && isset($_POST['q3'])) {

        $q1 = $_POST['q1'];
        if ($q1 == 1) {$q1a = "Blank Answer A";} ;
        if ($q1 == 2) {$q1a = "Blank Answer B";} ;
        if ($q1 == 3) {$q1a = "Blank Answer C";} ;
        echo $q1a;
        echo '<br>';

        $q2 = $_POST['q2'];
        if ($q2 == 1) {$q2a = "Blank Answer A";} ;
        if ($q2 == 2) {$q2a = "Blank Answer B";} ;
        if ($q2 == 3) {$q2a = "Blank Answer C";} ;
        echo $q2a;
        echo '<br>';

        $q3 = $_POST['q3'];
        if ($q3 == 1) {$q3a = "Blank Answer A";} ;
        if ($q3 == 2) {$q3a = "Blank Answer B";} ;
        if ($q3 == 3) {$q3a = "Blank Answer C";} ;
        echo $q3a;
        echo '<br>';                

        } else { 
        echo "Please check all fields"; 

}
?>

2 个答案:

答案 0 :(得分:2)

更改

if(isset($_POST['q1']) && isset($_POST['q2']) && isset($_POST['q3'])) {
  ... 
}
else {
  ...
}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
  if(isset($_POST['q1']) && isset($_POST['q2']) && isset($_POST['q3'])) {
    ... 
  }
  else {
    ...
  }
}

这样,除非发布了一些数据,否则不会显示错误消息。

答案 1 :(得分:0)

这样做:

//check if submit button has been clicked
if(isset($_POST['btnSubmit'])){

  if(isset($_POST['q1']) && isset($_POST['q2']) && isset($_POST['q3'])) {

        $q1 = $_POST['q1'];
        if ($q1 == 1) {$q1a = "Blank Answer A";} ;
        if ($q1 == 2) {$q1a = "Blank Answer B";} ;
        if ($q1 == 3) {$q1a = "Blank Answer C";} ;
        echo $q1a;
        echo '<br>';

        $q2 = $_POST['q2'];
        if ($q2 == 1) {$q2a = "Blank Answer A";} ;
        if ($q2 == 2) {$q2a = "Blank Answer B";} ;
        if ($q2 == 3) {$q2a = "Blank Answer C";} ;
        echo $q2a;
        echo '<br>';

        $q3 = $_POST['q3'];
        if ($q3 == 1) {$q3a = "Blank Answer A";} ;
        if ($q3 == 2) {$q3a = "Blank Answer B";} ;
        if ($q3 == 3) {$q3a = "Blank Answer C";} ;
        echo $q3a;
        echo '<br>';                

   } else { 
     echo "Please check all fields"; 
   }
}