データベースから10問ランダムに配列で取得して、その正当数をJSのアラートで表示したいのですが、
返り値のコードがおかしいのか、正解の選択肢を入れて回答しても正当数0で表示されてしまいます。
JSにはあまり詳しくなく、どなたかお力をお借りできないでしょうか?```
<テーブル:quiz>
<カラム:id / question / choice_1 / choice_2 / choice_3 / answer />
コード <!DOCTYPE html> <html> <head> <title>Sample Quiz</title> </head> <body> <?php $dsn='mysql:host=localhost;dbname=quiz'; $user='root'; $password='root'; try{ $db=new PDO($dsn,$user,$password); $db ->setAttribute(PDO::ATTR_EMULATE_PREPARES,false); $sql="SELECT * FROM quiz ORDER BY RAND()"; $stmt=$db->query($sql); $stmt->execute(); }catch(PDOException $error){ echo "error".$error->getMessage(); } ///////////////////////////////////////////////////////////////////////////// DB $id='id'; $question='question'; $choice_1='choice_1'; $choice_2='choice_2'; $choice_3='choice_3'; $number=0; $number = 0; for($i=0;$row=$stmt->fetch(); $i++){ $number++; $id = $row['id']; $question = $row['question']; $ans_array = array($row['choice_1'],$row['choice_2'],$row['choice_3']);{ } shuffle($ans_array); ?> <h4> <?php echo $number . ".) " . $question; ?></h4> <label><input type="radio" value="<?php echo $ans_array[0]; ?>" name="<?php echo $question; ?>"> <?php echo $ans_array[0]; ?></label> <label><input type="radio" value="<?php echo $ans_array[1]; ?>" name="<?php echo $question; ?>"> <?php echo $ans_array[1]; ?></label> <label><input type="radio" value="<?php echo $ans_array[2]; ?>" name="<?php echo $question; ?>"> <?php echo $ans_array[2]; ?></label> <?php}?> <br><br> <button onclick="returnScore()">View Results</button> <script> ///////////////////////////////////////////////////////////////////// Showing total score var ans = []; var answers = []; answers[0]="Japanese"; answers[1]="Sushi"; answers[2]="Abe"; answers[3]="Yen"; answers[4]="JAL"; answers[5]="Tokyo"; answers[6]="Naruto"; answers[7]="Reiwa"; answers[8]="Line"; answers[9]="Kento"; function getScore(){{ var score=0; var numQuestion=10; return score ; return numQuestion ; } score = getScore(); for(var i=0;i<=numQuestion;i++){ if(ans[i]==answers[i]){ score+=1; } else{ score +=0; } } } function returnScore(){ console.log('test') alert("Your Score is" + getScore()+"/10"); } </script> </body> </html>
回答1件
あなたの回答
tips
プレビュー