代码点火器下拉列表仅从数据库检索最后数据



我将 CI 表单与form_dropdown助手一起使用并尝试将 Mysql 数据拉入其选项,从下面的代码中,它只从 db 检索最后一条记录到选项列表中?

请告知我的代码有什么问题?

 public function getStates() {
    $query = $this->db->get('states');
    $return = array();
    if($query->num_rows() > 0){
        $return[''] = 'please select';
        foreach($query->result_array() as $row){
            $return[$row['state_id']] = $row['state_name'];
        }
    }
    return $return;
}

控制器

$this->load->model('db_model');
$data['options'] = $this->db_model->getStates();
$this->load->view('create_new', $data);

视图

$state = array(
'name' => 'state',
'id' => 'state',
//'value' => set_value('state', $state)
);
<?php echo form_label('State', $state['id']); ?>
<?php echo form_dropdown($state['name'], $options); ?>
<?php echo form_error($state['name']); ?>
<?php echo isset($errors[$state['name']])?$errors[$state['name']]:''; ?>

这样将完整的查询结果从模型发送到视图

 public function getStates() {
    $query = $this->db->get('states');
    return $query->result();
}

控制器保持原样,现在您可以在下拉列表中填充状态,如下所示:

视图

<?php
foreach($options as $opt){
  $options[$opt->state_id]=$opt->state_name;
}
echo form_dropdown($state['name'], $options);
?> 

试试这个:

function getStates() {
    $return = array();
    $query  = $this->db->get('states')->result_array();
    if( is_array( $query ) && count( $query ) > 0 ){
        $return[''] = 'please select';
        foreach($query as $row){
            $return[$row['state_id']] = $row['state_name'];
        }
    }
    return $return;
}

最新更新