使用CodeIgniter </select>动态填充<select>和mysql数据

时间:2013-07-29 13:37:15

标签: php mysql codeigniter templates

我对此事感到困惑。我有一个从mysql数据库中检索数据的模型

class load_model extends CI_Model{
function __construct(){
parent::__construct();
}
Function loadsuppliers()
{       
    $this->db->select('SupplierID, Name');
    $records=$this->db->get('supplier');
    $data=array();

    foreach ($records->result() as $row)
    {
        $data[$row->SupplierID] = $row->Name;
    }
    return ($data);
}

} ?&GT;

此模型将值提交给我的控制器中的函数

public function getSupplier()
{
    $this->load->model('load_model');
    $data['unit'] = $this->load_model->loadsuppliers();
    $this->load->view('SupplierMGT', $data);

}

我希望将检索到的数据作为组合框显示在我的视图中。我试图检查我是否能够使用echo json_encode($data)检索数据库值并返回{"unit":{"2":"test","3":"Delta"}}

你可以帮我这个吗?我尝试使用

<?php foreach($unit as $result):
print_r($result); 
endforeach;?>

检查我是否能够传递该值但是我失败了。

1 个答案:

答案 0 :(得分:1)

模型中的小变化:

function loadsuppliers()
{       
    $this->db->select('SupplierID, Name');
    $records=$this->db->get('supplier');
    $data=array();
    if($records->num_rows() > 0){
        $data   = $records->result_array();
    }
    return ($data);
}

在你看来SupplierMGT.php写下这个:

<select name="" id="" multiple="">
    <?php
        if(isset($unit) && is_array($unit) && count($unit) > 0){
            foreach($unit as $key=>$each){

    ?>
    <option value="<?=$each['SupplierID']?>"><?=$each['Name']?></option>
    <?php
            }
        }
    ?>
</select>
相关问题