douduan3203
douduan3203
2018-07-31 17:27
浏览 187
已采纳

使用Laravel将用户的选择与数据库中的记录进行比较

I have 4 radio button and the user can choose a single choice of them, I want to check if this choice exists or not in the table question(this table contains the text of question, thei options, and the correcte answer) if it exists I want to increment the fields points Which is in the table test, and for do that the controller contains :

$userChoise = $request->answer;
$test = new Test;
$questions = DB::table('question')->get();

    foreach ($questions as $question) {
       if ($question->correcte == $userChoise) {

             $test->nbr_points = 10;
             $test->save();

         }else{

             $test->nbr_points = 0;
             $test->save();
            }
        }

the problem is that it does not take into consideration what is in the condition if it still runs the else processing

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dtqscvrzn968518698
    dtqscvrzn968518698 2018-07-31 18:20
    已采纳

    Lets revise your code a bit =)

    $userChoise = $request->answer;
    $test = new Test;
    $correctAnswers = DB::table('question')->where('correcte', $userChoise)->count();
    
    $test->nbr_points = $correctAnswers * 10;
    $test->save();
    

    Is that what you're looking for?

    点赞 评论

相关推荐