I'm making a series of quizzes for a website I'm working on and am having a bit of trouble saving the user data. The structure is a bit odd, so that may have something to do with the problems coming up. My quiz controllers are labelled as Quiz1, Quiz2, and so on, and load a function called Quizzer, which is listened to in jquery. Whenever a radio button is clicked on the quiz page, jquery activates Quizzer to record the user input. Here is the sample code:
This is the code that loads the page:
public function Quiz4(){
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->model("quiz_model");
$this->data['choices'] = $this->quiz_model->get_records('quiz_4');
$this->load->view("student/quiztest", $this->data);
$quiz = 4;
$this->Quizzer($quiz);
$this->load->view("site_footer");
}
The value 4 is passed to Quizzer so it knows which quiz to write to in the database.
This is the controller Quizzer:
public function Quizzer($qid){
$this->load->model("quiz_model");
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'answer' => $this->input->post('answer')
);
$question = $this->input->post('question');
echo $qid;
$this->quiz_model->update_record($data, $user_id, $qid, $question);
}
$user_id tells which user is logged in $data and $question identify which radio button the user clicked from which group.
$qid should indicate which quiz page the user is on, and in the case of this test it echoed out a 4, so I know that it is picking up data, but it still won't write to the database. I found that manually typing in 4 instead of $qid would make the function work, but the current $qid variable won't be accepted.
This is the model function that does the saving to the database:
function update_record($data, $uid, $quiz, $question)
{
echo $quiz;
$this->db->where('uid', $uid);
$this->db->where('quiz', (int)$quiz);
$this->db->where('question', $question);
$this->db->update('quiz_results', $data);
}
I tried casting $quiz to int in an attempt to get the data types to match, but this trick is not working either. Based on how the function behaves when I manually type in a 4 versus passing it as a variable makes it seem like it's a problem with the type of data(which is why I tried to typecast).
If your
quiz_model
is designed correctly, instead of this:..you should be doing:
Also, you should have a single
Quiz
controller, not multipleQuizN
controllers. And finally, it's generally considered bad design to have controllers call other controllers. I've gotten into situations where I felt I had to, but it should be avoided. To that end, what does yourQuiz
controller offer that yourQuizzer
controller couldn't encapsulate so that you have noQuiz
controller at all?Cheers