2013-11-09 110 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']; 
} 
相關問題