如何从数据库中获取数据并在html下拉列表中显示?

时间:2018-01-10 14:46:00

标签: php html codeigniter codeigniter-3

我正在创建一个包含First_name,Last_name,city等字段的简单表单。因此,对于city字段,我想显示动态数据。下面是我在PHP CodeIgniter中使用它的代码。

控制器页面:

public function city()
    {
        $this->load->model('dropdownM');
        $getcity=$this->dropdownM->get_city();
        $this->load->view('form1city',$getcity);
    }

模特页面:

<?php

class DropdownM extends CI_Model
{
    public function get_city()
    {


        $this->db->select('fname');
        $this->db->from('city');
        $query = $this->db->get();
        if($query->num_rows()>0)
            {
            return $query->result();

        }
    }
}

查看页面:

    <form action="<?php echo base_url(); ?>index.php/Rec/user" method="post">

    <select class="form-control" id="city" name="city">

    <option value="">Select </option>
        <?php if(count($getcity)):?>

            <?php foreach($getcity as $city):?>

                <option value=<?php echo $city->c_id;?>><?php echo $village1->C_name;?></option>

            <?php endforeach;?>

        <?php else:?>

       <?php endif;?>

    </select>
       <center>                                            
       <input type="submit" value="Submit" class="btn btn-bricky" id="subbtn" 
        name="submit1">
       </center>
<form>

它没有在下拉列表中显示任何内容。我无法找出问题所在。

1 个答案:

答案 0 :(得分:3)

传递这样的数据

$data['getcity']=$this->dropdownM->get_city();
$this->load->view('form1city',$data);

并在视野中

<?php if(count($getcity) > 0):?>
    <select class="form-control" id="city" name="city">
        <option value="">Select </option>
            <?php foreach($getcity as $city):?>

                <option value=<?php echo $city['c_id'];?>><?php echo $village1['C_name'];?></option>

            <?php endforeach;?>
    </select>
<?php else:?>
    <p>No Category Found</p>
<?php endif;?>

在模型中

$this->db->select('fname');
$this->db->from('city');
$query = $this->db->get();
return $query->result_array();