0
votes

I use Codeigniter and have a form with multiple select box which is allow user to grab several options, I was stumbled on how to insert multiple selected values into database, the argument to hold multiple values is $category, currently the table is only inserted the last value from what I were selected.

here is my code:

Model:

function save_listing($user_id, $cname, $reg_code, $desc, $category)
{

    $data = array(
        'user_id' => $user_id,
        'company_name' => ucwords(strtolower($cname)),
        'register_code' => $reg_code,
        'descriptions' => $desc,
        'category_id' => $category
    );

    $this->db->insert('listing', $data);

    return TRUE;

}

Controller:

public function create()
{
    if(!$this->tank_auth->is_logged_in()) {
        redirect('/auth/login');

    }else{

        $user_id = $this->session->userdata('user_id');
        $profile = $this->users->get_profile_by_id($user_id);

        $this->form_validation->set_rules('cname', 'Company Name', 'trim|required|xss_clean|min_length[5]|max_length[50]|is_unique[listing.company_name]');
        $this->form_validation->set_rules('reg_code', 'Company No.', 'trim|xss_clean|min_length[5]|max_length[10]');
        $this->form_validation->set_rules('desc', 'Descriptions', 'trim|xss_clean|min_length[25]|max_length[500]');
        $this->form_validation->set_rules('category', 'Category', 'required');


        if($this->form_validation->run()) { // validation ok

            if(!is_null($data = $this->db_model->save_listing(
                $user_id,
                $this->form_validation->set_value('cname'),
                $this->form_validation->set_value('reg_code'),
                $this->form_validation->set_value('desc'),
                $this->form_validation->set_value('category')
            ))) { // success

                $this->session->set_flashdata('msg', 'Saved!');
                redirect(current_url());
            }

        }else{

            $errors = $this->tank_auth->get_error_message();
            foreach($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
        }

        $data['catOpts'] = $this->db_model->getCategories();
        $data['s_cate'] = $this->input->post('category');

        $this->load->view('header', $data);
        $this->load->view('create_new', $data);
        $this->load->view('footer', $data);

    }

}

I print_r('s_cate') which is post $this->input->post('category') selected values in view, it shown:

Array ( [0] => 1 [1] => 5 [2] => 7 )

Can anyone please provide a solution on how to serialize multiple values and insert into table?

Thanks.

1

1 Answers

0
votes

try something like this,Save your value as CSV in database

    $var = $this->input->post('category');//array(1,5,4);
    $data['s_cate'] =  implode(",", $var);