如何在php中提交单击时验证答案并显示答案

时间:2013-08-13 15:37:43

标签: php mysql ajax

在我的数据库中,我有2个表用于问题,1个表用于答案。

现在,问题是,当我点击答案并提交时,应该在点击时在div的同一页面上显示它是否正确,显示它是否正确。

代码在这里:

<?php 
  session_start();
  require_once("scripts/connect_db.php");
  $arrCount = "";

  if(isset($_GET['question'])){
     $question = preg_replace('/[^0-9]/', "", $_GET['question']);
     $output = "";
     $answers = "";
     $q = "";
     $dv="";
     $dv2="";


     $singleSQL = mysql_query("SELECT * FROM questions WHERE id='$question' LIMIT 1");
     while($row = mysql_fetch_array($singleSQL)){
        $id = $row['id'];
        $thisQuestion = $row['question'];
        $type = $row['type'];
        $subject =$row['subject'];
        $exam =$row['exam'];
        $explan =$row['explan'];
        $question_id = $row['question_id'];
        $s ='<strong>'.$subject.'</strong>';
        $e ='<small>'.$exam.'</small>';
        $q = '<h2>'.$thisQuestion.'</h2>';
        $ex ='<div id="welcomeDiv" style="display:none;" class="expl" >'.$explan.'</div>';
        $sql2 = mysql_query("SELECT * FROM answers WHERE question_id='$question' ORDER BY rand()");
        while($row2 = mysql_fetch_array($sql2)){
            $answer = $row2['answer'];
            $correct = $row2['correct'];
            $answers .= '<table class="table table-hover table-bordered"> <tr>
            <td class="chk"><label style="cursor:pointer;"><input type="radio" name="rads" value="'.$correct.'">'.$answer.'</label></td>
            </tr></table>
            <input type="hidden" id="qid" value="'.$id.'" name="qid"><br />
            ';

            $answer=$_POST[$correct];
            if(isset($answer)&&$correct==1){

            echo    $dv.='<div style="display:none; color=green;" id="welcomeDiv" id="dv">Your answer '.$answer.'  is correct</div>';}

            else{
                 $dv2.='<div style="display:none; color=red;" id="welcomeDiv" id="dv2">Your answer '.$answer.'  is worng</div>';}



        }
        $output = ''.$s.','.$e.''.$q.','.$dv.''.$dv2.''.$answers.''.$ex.'<input type="button" name="answer" value="check" onclick="showDiv();check_asnwer()" id="" />';
        echo $output;
       }
    }


  ?>

我正在尝试它,但它显示我这样的错误:

     Notice: Undefined index: 0 in F:\wamp\www\quiz\questions.php on line 38
     Notice: Undefined index: 1 in F:\wamp\www\quiz\questions.php on line 38
     Notice: Undefined index: 0 in F:\wamp\www\quiz\questions.php on line 38
     Notice: Undefined index: 0 in F:\wamp\www\quiz\questions.php on line 38

我的代码有任何问题,请帮助我,我需要这个来完成我的项目。

提前谢谢

1 个答案:

答案 0 :(得分:0)

        $answer=$_POST[$correct];
        if (isset($answer)) {

应该是

        if (isset($_POST[$correct])) {
            $answer = $_POST[$correct];

你不能尝试从一个可能未定义的值中分配FROM,然后在病房后测试是否存在。你必须直接测试存在的$ _POST值,然后在你确认它确实存在之后进行分配。