2013-11-09 71 views
0

我已经花了很多时间在这个多选的数组中,它在多个下拉框中保存多个值,我想要的是将选定的值插入到表中。Codeigniter插入多个选定的值到数据库中

让的说我被选中1,2,3下拉框中,当我的print_r($这个 - >输入 - >后( '类'))`,它显示

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

然而,当插入到表中,其只插入最后一个值而不是所有3个值。

这里是查看选择几个值:

$category = array(
    'name' => 'category', 
    'id' => 'category' 
); 

<select name="category[]" id="<?php echo $category['id'] ?>" multiple="multiple"> 
        <?php 
        foreach($catOpts as $catOpt) 
        { 
         $selected = ($this->input->post('category')==$catOpt->category_name) ? 'selected' : ''; 
         echo '<option value="'.$catOpt->category_id.'" '.$selected.'>'.$catOpt->category_name.'</option>'; 
        } 
        ?> 
       </select> 

控制器,我值传递到验证,如果验证有效,:

$this->form_validation->set_rules('category[]', 'Category', 'required'); 

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

    if(!is_null($data = $this->db_model->save_listing(   
     $this->form_validation->set_value('category[]') 
    ))) { // success 

    //some message to acknowledge success created. 

    } 
} 

模式插入到表:

function save_listing($category) 
{ 

    $data = array(
     'category_id' => $category 
    ); 

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

    return TRUE; 

} 

我不知道如何将所有值(数组)传递到控制器$this->form_validation->set_value('category[]'),然后执行模型函数save_listing()并将所有值保存到数据库的列中。

请帮助解决我的问题,我已经浏览了很多论坛,但没有运气得到解决方案。

谢谢。

回答

0

当你的领域是一个数组,你必须:

$data= array(); 

while($v = $this->form_validation->set_value("field[]")) 
{ 
    $data[] = $v; 
} 

,如果你不这样做,它返回的最后一个值。

您也可以通过$this->input->post('fields')获取值,但您的理智规则不会应用于值,如htmlspecialchars。

当然,这不是指定到文档,像其他的东西..

来源/system/libraries/Form_validation.php:

/** 
* Get the value from a form 
* 
* Permits you to repopulate a form field with the value it was submitted 
* with, or, if that value doesn't exist, with the default 
* 
* @access public 
* @param string the field name 
* @param string 
* @return void 
*/ 
public function set_value($field = '', $default = '') 
{ 
    if (! isset($this->_field_data[$field])) 
    { 
     return $default; 
    } 

    // If the data is an array output them one at a time. 
    //  E.g: form_input('name[]', set_value('name[]'); 
    if (is_array($this->_field_data[$field]['postdata'])) 
    { 
     return array_shift($this->_field_data[$field]['postdata']); 
    } 

    return $this->_field_data[$field]['postdata']; 
} 
相关问题