1

How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:

id userid   q_id        answer_id   time_taken
1   1      1,2,3,4,5    2,3,4,5,3    4,5,7,6,7

in my controller:

    public function insert_result()
         {
    $this->load->model('quiz_models');
    $user_id=$this->input->post('user_id');
    $qq_id=$this->input->post('questionid');
    $answer_id=$this->input->post('AnswerID');
    $time_taken=$this->input->post('timetaken');
    $question_no=$this->input->post('question_no');
    $bd = "$question_no";
    switch ($bd) {
    case"1":
    $data=array('user_id'=>$user_id,
                'q_id'=>$qq_id,
                'answer_id'=>$answer_id,
                'time_taken'=>$time_taken);
     $this->quiz_models->insert_result($data);     

    break;
    case"2":
    quiz_test();
    break;
    case"3":
    quiz_test();
    break;
    case"4":
    quiz_test();
    break;
    case"5":
    quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
        echo "something is wrong";
}
}
public function quiz_test()
     {
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
            'answer_id'=>$comma1,
            'time_taken'=>$comma2);
$this->quiz_model->update_result($data);     
}
}
}

and Model:

function insert_result($data)
     {
     $this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
     }
function quiz_test()
     {
$ses_id = $this->session->userdata('lastids');
          $sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
          $query = $this->dbb->query($sql);
          $result = $query->result();
          return $result;
     }
function update_result($data){
 $ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}

when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong

Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Naveen mutharasi
  • 105
  • 1
  • 10

1 Answers1

0

First of all - i think you've a major problem in your DB structure

Normalize your Data

You should prevent to store your information in the table like that. It should be possible to normalize your data properly. If you dont know how to do that the following link could be interesting:

Normalization in MYSQL

However a possible solution would be to structure your data:

In order to do that - create a save Method in your Model to split between update and insert - this model could look like

class Quiz_Models
{
    
    private $arrPostData;
    
    public function save($arrPostData = false)
    {
        $this->arrPostData = (!$arrPostData)    ?   $this->input->post()    :   $arrPostData;
        
        $id = $this->session->userdata("lastids");
        
        if ($id)
        {
            $query = $this->db
                ->select("*")
                ->from("results")
                ->where("id",$id)
                ->get();
                
            if ($query->num_rows() == 1)
            {
                $this->update($query->row(0));
            }
            else return false;
        }
        else
        {
            $this->insert();
        }

        if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
    }   
    
    private function update($objData)
    {
        $objCollection = new Quiz_Collection();
        $objCollection->userId = $objData->userid;
        $objCollection->id = $objData->id;

        
        $arrData = explode($objData->q_id);
        foreach($arrData AS $key => $quizId)
        {
        
            $objQuiz = new stdClass();
            $objQuiz->q_id = $quizId;
            $objQuiz->answer_id = explode($objData->answer_id)[$key];
            $objQuiz->time_taken = explode($objData->answer_id)[$key];
            
            $objCollection->append($objQuiz);
        }
        

        $objQuizFromPost = new stdClass();
        $objQuizFromPost->q_id = $this->arrPostData["questionid"];
        $objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
        $objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
        
        $objCollection->addQuizFromPost($objQuizFromPost);
        
        $this->db
            ->where("id",$objCollection->id)
            ->update("results",$objCollection->getDbData());
    }
    
    private function insert()
    {
        $objCollection = new Quiz_Collection();
        $objCollection->userId = $this->arrPostData['user_id'];
        
        $objQuizFromPost = new stdClass();
        $objQuizFromPost->q_id = $this->arrPostData["questionid"];
        $objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
        $objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
        
        $objCollection->addQuizFromPost($objQuizFromPost);
        
        $this->db->insert("results",$objCollection->getDbData());
        
        $this->session->set_userdata("lastids", $this->db->insert_id());
        
    }

}

as an addition you need a Collection Object (put this below your model)

class Quiz_Collection extends Array_Object
{
    public $userId = 0;
    public $id = 0;
    
    public function addQuizFromPost($objQuiz)
    {
        if (intval($objQuiz->q_id) > 0)
        {
            foreach($this AS $key => $obj)
            {
                if ($obj->q_id == $objQuiz->q_id)
                {
                    $this->offsetSet($key, $objQuiz);
                    return true;
                }
            }
            
            $this->append($objQuiz);
            return true;
        }
        return false;
    }
        
    public function sortQuizData($objA, $objB)
    {
        if ($objA->q_id == $objB->q_id) return 0;
        return ($objA->q_id < $objB->q_id)  ?   -1  :   1;
    }
    
    public function getDbData()
    {
        $this->uasort(array($this,"sortQuizData"));
        $arrData = $this->getArrayCopy();
        
        $arrDbData = [
            "userid" => $this->userId,
            "q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
            "answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
            "time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
        ];
        
        return $arrDbData;
    }
}

pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.

Community
  • 1
  • 1
Atural
  • 5,389
  • 5
  • 18
  • 35