PHP 测验实际上并没有检查答案是否正确,而是总是说正确

PHP Quiz not actually checking if answer is correct, rather always saying correct

我有一个奇怪的问题,我的 PHP 测验没有检查用户提交的答案是否真的正确。我知道这一点,因为当我回答完全不正确的问题时,它仍然会回复 if correct 消息,并且不会执行 link 如果答案错误则应该显示的内容。起初我以为这是因为我检查的是数组中的短语而不是单个单词,但在用简单的单个单词测试后我得到了相同的结果。我对 PHP 比较陌生,一直在网上搜索,但我只找到与多项选择答案相关的答案,而不是提交文本框。这是我的代码:

数组列表:

<?php
$array['one'] = "Mickey Mouse";
$array['oneone'] = "Oswald the Lucky Rabbit";
?>

测验主页面:

<!DOCTYPE html>
<html>
<head>
<title>Final Quiz</title>
</head>
<body>
<?php
include("newquiz2.php");
 print("{$array['one']} was modeled after what character created by the Disney Studio?<br>");
 print("<form action='newquiz2check.php' method='get'>\n");
 print("<input type='text' name='one'><br><br>\n");
 print("<input type='submit' value='Submit Answer'>\n<br><br>");
 print("</form>\n\n\n");

?>
</body>
</html>

测验检查:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Answers for Quiz</title>
</head>
<body>
<?php
include("newquiz2.php");
if (metaphone($one) == metaphone($oneone)) {
$one = $array['one'];
$oneone = $array['oneone'];
   print("Correct: $one was modeled after $oneone");
   print("<p><a href='newquiz2ask.php'>Play again </a><br><br>");
   }  
else{print("<a href='newquiz2ask.php'>Back to home </a><p>\n");}



?>
</body>
</html>

除此之外一切正常。我应该使用 @GET 将变量分配给数组还是什么?我不确定这是否是您检查提交文本框的方式。

测验非常广泛应用但是根据你的尝试和评论,我有一些东西给你(非常基础数组基于测验)。

questions.php

<?php
$questions = array(
    array("question"=>"Question number 1", "answer"=>"ans1"),
    array("question"=>"Question number 2", "answer"=>"ans2"),
    array("question"=>"Question number 3", "answer"=>"ans3"), 
);
?>

index.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
        require_once 'questions.php';
        ?>
        <form method="post" action="check.php">
            <?php 
            $random_index = array_rand($questions,1); //gives you only one question index from 3 question list
            ?>
            <label><?php echo $questions[$random_index]['question']; ?></label><br>
            <input name="answer" type="text" /><br>
            <input type="hidden" name="index" value="<?php echo $random_index; ?>" />
            <input type="submit" value="submit answer" />
        </form>
    </body>
</html>

check.php

<?php
require_once 'questions.php';
$entered_answer = $_POST['answer']; //Form input named as answer
$index = $_POST['index'];
if($entered_answer==$questions[$index]['answer']){
    echo "Correct answer";
}
else{
    echo "Incorrect answer";
}
//Redirect link
?>

根据您的尝试,我创建了三个文件,index.phpquestions.phpcheck.php。尝试创建这些文件和 运行 index.php。查看数组中的答案并输入正确和错误的答案。

对于PHP数组,数组索引现在已经足够了,但是如果你要将问题和答案存储到你的数据库中,那么你需要有主键ID来获取答案并比较答案。