DBから問題を10問ランダムで表示し、その正当数をJSのアラートで表示させようとしているのですが、
私のコードではうまく正当数が反映されず、常に1/10で表示されてしまいます。
私のコードで足りないところがあればご教授願いたいです。
また私としては54行目のansに値がないためにこの問題が起きていると考えています。→function関数でユーザーが選択した回答を取得→正解(answer)と照合→一致したなら+1点というロジックで対応。したつもりなのですが、うまく作動しません。ロジックや考え方など自体が間違っているようでしたらご教授願いたいです。
<テーブル:quiz>
<カラム:id/question/choice_1/choice_2/choice_3/answer>
<html> <head> <title>Sample Quiz</title> </head> <body> <?php $dsn='mysql:host=localhost;dbname=ex.sql'; $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" oncick="choice" value="<?php echo $ans_array[0]; ?>" name="<?php echo $question; ?>"> <?php echo $ans_array[0]; ?></label> <label><input type="radio" onclick="choice" value="<?php echo $ans_array[1]; ?>" name="<?php echo $question; ?>"> <?php echo $ans_array[1]; ?></label> <label><input type="radio" onclick="choice" 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 choice(){ if ans=$ans_array===answers;{ score+=1 }else{ score+=0; } return choice; } 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; } } return score;//add } function returnScore(){ console.log('test') alert("Your Score is" + getScore()+"/10"); } </script> </body> </html> コード