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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog