Reputation: 1243
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
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)
Upvotes: 0
Views: 1370
Reputation: 838
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);
}
}
Upvotes: 2
Reputation: 16436
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
}
}
Upvotes: 0