首页 > 解决方案 > 我正在制作一个琐事游戏。每个答案都会显示正确的页面。我该如何解决?

问题描述

<?php
    if(array_key_exists('button1', $_POST)) {
        button1();
    }
    if(array_key_exists('button2', $_POST)) {
        button2();
    }
    if(array_key_exists('button3', $_POST)) {
        button3();
    }
    if(array_key_exists('button4', $_POST)) {
        button4();
    }
    function button1() {
        if ($correct == $answer1){
            header("Location: correct.php"); 
        }
        else 
            {header("Location: wrong.php");
            
        }
    }
    function button2() {
        if ($correct == $answer2){
            header("Location: correct.php"); 
        }
        else {
            header("Location: wrong.php");
            
        }
    }
    function button3() {
        if ($correct == $answer3){
            header("Location: correct.php"); 
        }
        else {
            header("Location: wrong.php");
            
        }
    }
    function button4() {
        if ($correct == $answer4){
            header("Location: correct.php"); 
        }
        else {
            header("Location: wrong.php");
            
        }
    }
?>

<form method="post">
    <input type="submit" name="button1"
            class="button" value="<?php echo $answer1?>" />
      
    <input type="submit" name="button2"
            class="button" value="<?php echo $answer2?>" />
            
    <input type="submit" name="button3"
            class="button" value="<?php echo $answer3?>" />
            
    <input type="submit" name="button4"
            class="button" value="<?php echo $answer4?>" />
</form>

这应该将正确答案与他们点击的任何内容进行比较,但由于某种原因,它总是说它是正确的。所有变量都在代码的前面定义,并且来自数据库。我尝试使用 javascript 进行 tis 但是我所有的变量都在 php 中,所以我无法比较答案。

标签: php

解决方案


当您测试答案时,您正在初始化超出范围的变量。

您有一些代码相当于:

    $answer1 = 1;
    $correct = 2;
    button1();

    function button1() {
        if ($correct == $answer1){
            header("Location: correct.php"); 
        }
        else 
            {header("Location: wrong.php");
            
        }
    }

在顶部初始化的变量超出了函数的范围。PHP 将函数内部的变量视为未定义的(因为它们没有被初始化)并将它们都赋值为 value null。因此测试通过,correct.php页面被加载。

您根本不需要这里的函数调用。你可以这样做

    if(array_key_exists('button1', $_POST)) {
        if ($correct == $answer1){
            header("Location: correct.php");
        }
        else {
            header("Location: wrong.php");
        }
    }

不过,我怀疑这里的真正解决方案从一开始就涉及不同的方法。

看看关于变量范围的 PHP 页面


推荐阅读