我使用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 )
有人可以提供一个关于如何序列化多个值并插入表格的解决方案吗?
感谢。
答案 0 :(得分:0)
尝试这样的方法,在数据库中将您的值保存为CSV
$var = $this->input->post('category');//array(1,5,4);
$data['s_cate'] = implode(",", $var);