简体   繁体   中英

insert data from foreach PHP containing an array

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)

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);
        }       
}

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
        }       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM