我在显示从数据库到下拉列表的数据时遇到了困难。
这是我尝试过的:
模型.php
public function __construct() { parent::__construct(); } function getAllGroups() { /* $query = $this->db->get('location'); foreach ($query->result() as $row) { echo $row->description; }*/ $query = $this->db->query('SELECT description FROM location'); foreach ($query->result() as $row) { echo $row->description; } //echo 'Total Results: ' . $query->num_rows(); }
Controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Delivery_controller extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('delivery_model'); } public function index() { $data['title']= 'Warehouse - Delivery'; $this->load->view('include/header',$data); $this->load->view('include/navbar',$data); $this->load->view('delivery_view', $data); $this->load->view('include/sidebar',$data); $this->load->view('include/footer',$data); $data['groups'] = $this->delivery_model->getAllGroups(); } }
View.php
<select class="form-control"> <?php $data = $this->delivery_model->getAllGroups(); foreach($description as $each) { ?><option value="<?php echo $each['description']; ?>"><?php echo $each['description']; ?></option>'; <?php } ?> </select>
但是结果显示在我的页面顶部。它没有出现在下拉列表中。我在这里做错了什么?非常感谢您的帮助。谢谢。
您不应该从视图中调用模型。而是$data['groups']在加载视图之前尝试调用模型和设置。
$data['groups']
也不要在模型中回显行结果,除非您希望将其显示在页面上。
控制器:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Delivery_controller extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('delivery_model'); } public function index() { $data['title']= 'Warehouse - Delivery'; $data['groups'] = $this->delivery_model->getAllGroups(); $this->load->view('include/header',$data); $this->load->view('include/navbar',$data); $this->load->view('delivery_view', $data); $this->load->view('include/sidebar',$data); $this->load->view('include/footer',$data); } }
模型:
public function __construct() { parent::__construct(); } function getAllGroups() { /* $query = $this->db->get('location'); foreach ($query->result() as $row) { echo $row->description; }*/ $query = $this->db->query('SELECT description FROM location'); return $query->result(); //echo 'Total Results: ' . $query->num_rows(); }
视图:
<select class="form-control"> <?php foreach($groups as $row) { echo '<option value="'.$row->description.'">'.$row->description.'</option>'; } ?> </select>