0

我使用 Codeigniter 并有一个带有多个选择框的表单,它允许用户获取多个选项,我偶然发现如何将多个选定值插入数据库,保存多个值的参数是$category,目前表只插入最后一个值从我被选中的。

这是我的代码:

模型:

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;

}

控制器:

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

    }

}

print_r('s_cate')是在视图中发布$this->input->post('category')选定的值,它显示:

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

谁能提供有关如何序列化多个值并插入表的解决方案?

谢谢。

4

1 回答 1

0

尝试这样的事情,将您的值保存为数据库中的 CSV

    $var = $this->input->post('category');//array(1,5,4);
    $data['s_cate'] =  implode(",", $var);
于 2013-11-09T08:43:14.260 回答