测验:无法使用rand()获得正确答案

时间:2019-11-18 23:43:02

标签: php html mysql session

我从technopoints那里获得了这段代码,我想从数据库中得到一个随机问题,但是当我将$fetchqry = "SELECT * FROM quiz ORDER BY rand()";放到rand()时,它无法得到正确的结果,因此我无法解决。我一直在尝试解决此问题,但该方法不起作用,如何为每个问题增加数字?

                                if (isset($_POST['click']) || isset($_GET['start'])) {
                                @$_SESSION['clicks'] += 1 ;
                                $c = $_SESSION['clicks'];
                                if(isset($_POST['userans'])) { $userselected = $_POST['userans']; 

                                $fetchqry2 = "UPDATE 'quiz' SET 'userans'='$userselected' WHERE 'id'=$c-1"; 
                                $result2 = mysqli_query($db,$fetchqry2);
                                }


                                } else {
                                  $_SESSION['clicks'] = 0;
                                }

                                //echo($_SESSION['clicks']);
                                ?>


<div class="bump"><br><form><?php if($_SESSION['clicks']==0){ ?> <button class="button" name="start" float="left"><span>START QUIZ</span></button> <?php } ?></form></div>
<form action="" method="post">          
<table>
  <?php if(isset($c)) {   $fetchqry = "SELECT * FROM 'quiz' ORDER BY rand()";
        $result=mysqli_query($db,$fetchqry);
        $num=mysqli_num_rows($result);
        $row = mysqli_fetch_array($result,MYSQLI_ASSOC); }
      ?>
<tr><td><h3><br><?php echo  @$row['que'];?></h3></td></tr> <?php if($_SESSION['clicks'] && $_SESSION['clicks']){ ?>
  <tr><td><input required type="radio" name="userans" value="<?php echo $row['option 1'];?>">&nbsp;<?php echo $row['option 1']; ?><br>
  <tr><td><input required type="radio" name="userans" value="<?php echo $row['option 2'];?>">&nbsp;<?php echo $row['option 2'];?></td></tr>
  <tr><td><input required type="radio" name="userans" value="<?php echo $row['option 3'];?>">&nbsp;<?php echo $row['option 3']; ?></td></tr>
  <tr><td><input required type="radio" name="userans" value="<?php echo $row['option 4'];?>">&nbsp;<?php echo $row['option 4']; ?><br><br><br></td></tr>
  <tr><td><button class="button3" name="click" >Next</button></td></tr> <?php }  
                                  ?> 
  <form>
 <?php if($_SESSION['clicks']){ 
  $qry3 = "SELECT 'ans', 'userans' FROM 'quiz';";
  $result3 = mysqli_query($db,$qry3);
  $storeArray = Array();
  while ($row3 = mysqli_fetch_array($result3, MYSQLI_ASSOC)) {
     if($row3['ans']==$row3['userans']){
     @$_SESSION['score'] += 1 ;
   }
}

 ?>

<h2>Result</h2>
 <span>No. of Correct Answer:&nbsp;<?php echo $no = @$_SESSION['score']; 
 session_unset(); ?></span><br>
 <span>Your Score:&nbsp<?php echo $no*2; ?></span>
<?php } ?>```

1 个答案:

答案 0 :(得分:-1)

我认为您的sql查询应该是这样的:

$fetchqry = "SELECT * FROM quiz ORDER BY rand() LIMIT 1";

我不太确定您是否必须将所有行显示为测验还是仅显示一行,如果是这样,请尝试使用LIMIT 1