将多个输入与数据库匹配

时间:2013-12-11 10:55:28

标签: php mysql mysqli

我正在尝试创建一个自测页面,其中php匹配数据库的输入并检查答案是否正确。但到目前为止,我不知道如何让它单独检查所有的答案。到目前为止,我得到的脚本只有在所有答案都错误的情况下才有效。我将如何在PHP中执行此操作?

到目前为止,这是我的代码:

    <?php 
    $host = "localhost";
    $user = "root";
    $pwd = "";
    $db_name = "flashcards";
    $link = mysqli_connect($host, $user, $pwd, $db_name)or die("cannot connect");

    $sql = mysqli_query($link, "SELECT * FROM Questions ORDER BY ID ASC LIMIT 25") or die(mysqli_error($link));
    echo "<form action='".$_SERVER['PHP_SELF']."' method='post'><table border='1'>";
    while ($rows = mysqli_fetch_assoc($sql))
        {
            echo "<tr><td value='".$rows['ID']."'>".$rows['Question']."</td><td><input type='text' name='Answer'></input></td></tr>";
        }  
    echo "</table><input type='submit' name='submit'>test</input></form>";
    if (isset($_POST['submit'])) 
    { 
        if ($_POST['Answer'] != $rows['Answer']) 
        {
        echo "wrong!";
        }
        else
        {
        echo "right";
        }
    }

    ?> 

1 个答案:

答案 0 :(得分:1)

问题在于:

<input type='text' name='Answer'></input>

问题在于所有答案输入都具有相同的“名称”,因此对于您回答的每个字段,值(答案字符串)都会被覆盖。

为了解决这个问题,您需要获得一系列答案,如下所示:

<input type='text' name='Answer[]'></input>

然后,通过它迭代:

foreach($_POST['Answer'] as $answer)
    if (isset($_POST['submit'])) 
        { 
            if ($answer != $rows['Answer'])
            //...
相关问题