doubei8168 2015-02-04 11:41
浏览 51
已采纳

CodeIgniter,将数据从模型传递到控制器以在视图中使用

I want to pass data queried in my model to the controller, to do so I am using return $data. Then in the controller I use $this->load->view('my_view', $data);

From my understanding var_dump($data); in the view should show me the results from the query... This is not the case. I am getting "undefined variable data" and NULL from the var_dump($data);.

Here is my model:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Manage_accounts_model extends CI_Model {


    public function index() {

        //

    }

    public function get_users(){

        $data = array();

        $data['query'] = $this->db->get('users');

        return $data['query'];

     }

}

Here is my controller

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Manage_accounts extends CI_Controller {

    public function index() {

        $this->load->view('template/header');

        $this->load->model('manage_accounts_model');

        $this->load->view('template/footer');

        $this->load->model('manage_accounts_model');

        $res = $this->manage_accounts_model->get_users();

        if($res){

            $this->load->view('manage_accounts_view', $data);

        } else {

            echo "Fail";

        }

  }

}

And finally my view:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
?>
<div class="container">

    <h1><?php if($title){ echo $title; } ?></h1>

    <?php var_dump($data['query']); ?>

</div>
  • 写回答

5条回答 默认 最新

  • dryift6733 2015-02-04 11:53
    关注

    I think you made 2 mistakes

    1. forget to fetch the result to an array
    2. forget to pass the data to view

    change in your model class.

    public function get_users(){
    
        $data = array();
        $query = $this->db->get('users');
        $res   = $query->result();        
        return $res;
    
     }
    

    change in your controller class

    public function index() {
    
        $this->load->view('template/header');
    
        $this->load->model('manage_accounts_model');
    
        $this->load->view('template/footer');
    
        $this->load->model('manage_accounts_model');
    
        $res = $this->manage_accounts_model->get_users();
    
        if($res){
            $data['result'] = $res;
            $this->load->view('manage_accounts_view', $data);
    
        } else {
    
            echo "Fail";
    
        }
    

    in your view

      print_r($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 wamp3.3.5安装完成后图标正常显示绿色,鼠标左右键点击图标均无反应。求解决方法。
  • ¥15 鼠标点击的这条记录了什么?
  • ¥15 在写pid调速的程序时,电机始终维持最大速度
  • ¥15 请问如何查看手机root记录?
  • ¥15 商城小程序订单号重复
  • ¥15 学校优化算法sbo和蚁群算法怎么结合
  • ¥21 matlab怎么求时域信号的二阶导数
  • ¥15 判断两个表是否完全相同
  • ¥15 java map类型数据格式,如何快速通过前缀匹配元素
  • ¥15 stc12c5a60s2、QMC5883L、LCD1602组合测量磁场所需程序