它总是说正确!我做错了什么?

时间:2017-06-11 10:51:29

标签: php

$number1 = mt_rand(1,9);
$number2 = mt_rand(1,9);

$total = $number1 * $number2;

echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";

if (isset($_POST['done'])) { 
    if (isset($_POST['num1']) == $total) {
        echo "Correct!";
    } else {
        echo "Wrong!";
    } 
 }

总是说正确!我不知道为什么(我是初学者),我只想检查num1是否等于$ total

3 个答案:

答案 0 :(得分:2)

您将isset($ var)与$ total进行比较。它们都是真实的,所以条件总是正确的,只要&#39; num1&#39;在POST数据中定义。

也许你应该这样做:

isset($_POST['num1']) && $_POST['num1'] == $total

你也应该投出#num;&#39;到一个数字

答案 1 :(得分:1)

您的代码中存在许多问题:

  1. 您必须首先检查帖子是否已提交,如果其格式错误,则表格

    if (isset($_POST['done'])) {
        //your code 
    }
    else {
        //your form
    }
    
  2. 在会话中保存$total以便在表单提交时重复使用它,在您的情况下,$ total每次都有不同的值

  3. isset()返回true或false如果要使用isset,则不能将true或false与整数值进行比较,您的代码必须如下所示:

    if(isset($_POST['num1']) && $_POST['num1'] == $total) {
    }
    

答案 2 :(得分:1)

正如Tom Udding所说,每次刷新页面时,它都会再次调用所有代码,因此将再次随机选择number1和number2。

您当前的代码无法保存以前的变量值。一种非传统的方式是添加隐藏的表单字段以及问题的答案,如下所示:

  <?php

 if (isset($_POST['done']) && isset($_POST['num1']))
     {
     //Get answer from form.
     $total = $_POST['answer'];

     if ($_POST['num1'] == $total)
         {
         echo "Correct!";
         } 
         else
         {
         echo "Wrong!";
         }
     }
 $number1 = mt_rand(1, 9);
 $number2 = mt_rand(1, 9);

 $total = $number1 * $number2;

 echo "<form method='post'>";
 echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";

//Added hidden form with answer.
 echo "<input type='number' hidden name='answer' value='$total' />";
 echo "<input type='submit' value='submit!' name='done'>";
 echo "</form>";
?>

<强>无论其...

在现实的富Web应用程序中,您不会将答案放在表单中供用户查看,您可以使用sessions在用户遍历时跟踪用户的信息(或者在您的情况下刷新)您的页面。

因此,对您的问题的更实际的答案如下:

<?php

 session_start();

 if (isset($_POST['done']) && isset($_POST['num1']))
     {
     $answer = $_SESSION['answer'];

     if ($_POST['num1'] == $answer)
         {
         echo "Correct!";
         } else
         {
         echo "Wrong!";
         }
     }
 $number1 = mt_rand(1, 9);
 $number2 = mt_rand(1, 9);

 $total = $number1 * $number2;
 $_SESSION['answer'] = $total;

 echo "<form method='post'>";
 echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
 echo "<input type='number' hidden name='answer' value='$total' />";
 echo "<input type='submit' value='submit!' name='done'>";
 echo "</form>";
?>