0

I am using the codeigniter framework, and I am running to a bit of a problem trying to save data from a form.

How do I insert a new row for each user_answer containing the other information?

Thanks!

This is my foreach loop in the controller and the call to the model

foreach($_POST as $key => $val)  
        {  
            $data[$key] = $this->input->post($key);  
        } 
$this->quiz_model->save_answers($data);

This is the model

function save_answers($data)
    {
            foreach ($data['user_answer'] as $key) {
                    $this->db->insert('answer', $data);
            }       
    }

Table is setup as

  • answer_id (auto increment)
  • quiz_id
  • question_id
  • user_id
  • user_answer

Var dumps

data => array(3) { ["user_id"]=> string(9) "anonymous" ["quiz_id"]=> string(2) "24" ["question_id"]=> string(2) "18" ["user_answer"]=> array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } }

data['user_answers'] => array(3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" }

error

Error Number: 1054

Unknown column 'Array' in 'field list'

INSERT INTO `answer` (`user_id`, `quiz_id`, `question_id`, `user_answer`) VALUES ('anonymous', '24', Array)
2
  • First I would use prepared statements, something codeigniter doesn't have. I would recommend you use mysqli in your model. You are vulnerable to sql injections. Commented Sep 4, 2017 at 3:54
  • @Robert Rocha as long as he is using db->insert his "All values are escaped automatically producing safer queries." Also, you can use PDO and mysqli queries. Per the codeigniter docuentation Commented Sep 5, 2017 at 3:44

2 Answers 2

2

You should create new set of data per user_answer. Try this:

function save_answers($data)
{
        foreach ($data['user_answer'] as $key) {
                $new_data = array('user_id' => $data['user_id'], 'quiz_id' => $data['quiz_id'], 'question_id' => $data['question_id'], 'user_answer' => $key)
                $this->db->insert('answer', $new_data);
        }       
}
Sign up to request clarification or add additional context in comments.

1 Comment

That was exactly what the doctor ordered!
0

You have issue in foreach loop. Change your save_answers method to :

function save_answers($data)
{
        foreach ($data['user_answer'] as $key=>$value) { //<------------change here
                $data_insert = array('user_id'=>$data['user_id'],'quiz_id'=>$date['quiz_id'],'question_id'=>$data['question_id'],'user_answer'=>$value); //create new array
                $this->db->insert('answer', $data_insert);//<------------change here
        }       
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.