php - 从 CodeIgniter 中的数据库获取下拉列表

标签 php mysql codeigniter

我是 CodeIgniter 的新手,我一直试图用数据库中的数据填充 View 页面上的下拉列表,但没有成功。我尝试使用这个问题的建议,但下拉列表仍然是空的 ( display data from database to dropdown CodeIgniter )

这是我的看法:

<label>City</label>
<select class="form-control>
    <option value="">All</option>
    <?php
    foreach($groups as $city)
    {
        echo '<option value="'.$city['cityidd'].'">'.$city['city'].'</option>';
    }
    ?>  
</select> <br/>

这是我的 Controller :

<?php 
class Main_controller extends CI_Controller 
{
    function __construct() 
    { 
         parent::__construct(); 
         $this->load->helper('url'); 
         $this->load->database(); 
    } 

      public function index() 
    { 
         $this->load->helper('form'); 
         $this->load->view('supplier_add'); 
    } 
}

这是我的模型:

class Site_model extends CI_Model
{
    public function __construct() 
    {
        /* Call the Model constructor */
        parent::__construct();
    }
    function getAllGroups()
    {
        $query = $this->db->query('SELECT city FROM citys');

        return $query->result();
    }
}

表名是“citys”那么对应的列头是“cityidd”和“city”

最佳答案

那里发现了几个问题。进行如下更改

 function __construct(){ 
    parent::__construct(); 
    $this->load->helper('url');
    $this->load_model('Site_model');
    $this->load->database(); 
} 
public function index(){ 
  $this->load->helper('form');
  $data['groups'] = $this->site_model->getAllGroups();
  $this->load->view('supplier_add',$data); 
} 

最后模型

function getAllGroups(){
    $query = $this->db->query('SELECT cityidd,city FROM citys');
    return $query->result_array();
}

现在测试

关于php - 从 CodeIgniter 中的数据库获取下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40257737/

相关文章:

php - 使用 php 从 mysql 中的 3 个表创建下载脚本

php - 在同一行插入更多值

javascript - 加载数据表复选框(如果数据库中有),已选中

php - 发生数据库错误错误号: 1242 when i try to access the user search page

php - 与 mysql 数据库不同的结果作为下拉列表/php

javascript - 如何在不重定向的情况下获取 PHP 脚本?

php - 如何修剪数组中每个键的最后两个字符?

php - 无法在数组元素中设置默认值 0

mysql - 使用查询连接多个表

CodeIgniter 路由总是通过 index.php?