Codeigniter form_helper getting database rows to be values in select menu

后端 未结 6 2157
借酒劲吻你
借酒劲吻你 2021-01-07 00:49

I am writing a form, which has a select menu in it, I want the values to pulled from the database, so I thought it would be something along these lines:

My view

6条回答
  •  庸人自扰
    2021-01-07 01:27

    You need to pass an array to your dropdown, where the array key will be the value that is POSTed and the value will the text that is displayed.

    To achieve this, change your controller like so:

    function add_content() {
            $data = array();
            $this->is_logged_in();
            $this->load->model('category_model');
            $data['select_options'] = $this->category_model->get_all_online_select();
            $this->load->view('admin/content/add_content', $data);
    }
    

    and add this function to your model

    public function get_all_online_select() {
            $this->db->select('id, name'); //change this to the two main values you want to use
            $this->db->from('category');
            $this->db->where('category_online', 1);
            $query = $this->db->get();
            foreach($query->result_array() as $row){
                $data[$row['id']]=$row['name'];
            }
            return $data;
    }
    

    That should do the trick

提交回复
热议问题