我使用带有form_dropdown
帮助器的CI表单并试图将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']]:''; ?>
答案 0 :(得分:0)
将完整的查询结果从模型发送到视图,如此
<强>模型强>
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);
?>
答案 1 :(得分:0)
试试这个:
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;
}