如何在codeigniter中的数据库中存储多个选择框值?

时间:2017-02-07 06:00:47

标签: php mysql codeigniter

我的页面中有一个需求表单。在该表单中,我有用户下拉列表和选择框。我想一次选择多个用户,并且需要将所选用户存储在数据库中。

控制器:

public function requirement()
{
    $this->load->model('LoginModel');
    $data['user'] = $this->LoginModel->getusers();
    $this->load->view('Admin/requirements',$data);

    $insert = array (
      'role_name'             => $this->input->post('role_name'),
      'vacancies'             => $this->input->post('vacancies'),
      'experience'            => $this->input->post('experience'),
      'jd'                    => $this->input->post('jd'),
      'hiring_contact_name'   => $this->input->post('hiring_contact_name'),
      'hiring_contact_number' => $this->input->post('hiring_contact_number'),
      'user_id'               => $this->input->post('user_id')//this is my foreign key id from users table);
    );
    $this->LoginModel->add_requirement($insert);
}

型号:

function getusers()
{
    $this->db->select('*');
    $this->db->from('users');
    $query = $this->db->get();
    //echo $this->db->last_query();
    return $query->result();
}

查看页面

<div class="form-group">
    <label>Choose Vendor</label>
    <select id="chkveg"class="form-control" multiple class="form-control" data-placeholder="user name"  name="user_id[]" >
        <option value="0"></option>
        <?php
        print_r($user);
        foreach ($user as $rows)
        {
            ?>
            <option value="<?php echo $rows->user_id ?>">
                <?php echo ucfirst($rows->first_name) ?>
            </option>
            <?php
        }
        ?>
    </select>
</div>

2 个答案:

答案 0 :(得分:1)

制作选择框数组而不是单个数值。

<select id="chkveg""  class="form-control" multiple class="form-control" data-placeholder="user name"  name="user_id[]" >

比您需要将列数据类型改为varchar或text。

之后你可以内爆函数来创建像

这样的字符串值
'user_id'=> implode(',',$this->input->post('user_id')); //eg.1,2,3

参考链接:http://www.w3schools.com/php/func_string_implode.asp

答案 1 :(得分:0)

您应该使用'user_id'=>implode(',',$this->input->post('user_id'));将数组转换为逗号分隔值。之后,您可以将其存储到数据库表中。因为您无法直接将数组存储到数据库表中