Codeigniter: Passing data from controller to view

后端 未结 13 2155
忘了有多久
忘了有多久 2020-11-27 06:57

I want to pass $data from the controller named poll to the results_view however I am getting an undefined variable error.

         


        
13条回答
  •  星月不相逢
    2020-11-27 07:23

    Ok so I finally solved it. You should really have a model (it helps a lot)

    In your model do something like

    Model

    class poll_model extends CI_MODEL {
    
     function __construct() {
       $this-load->database(); 
     }
    
     function get_poll {
       $this->db->query("SELECT * FROM table");
       $row = $query->row();
    
       $obj = array(
        'id' => $row->id
      );
       return $obj;
     }
    }
    

    Now if you have more than an id say name of poll # you can add in array. Now in your controller do

    class Poll extends CI_Controller {
    
    public function __construct()
       {
            parent::__construct();
            $this->load->database();
            $this->load->helper('form');
            $this->load->model('poll_model');
       }
    
    public function index()
    {
        $data["a"] = $this->poll_model->get_poll();
        $this->load->view('poll_view',$data);
    }
    

    And finally in VIEW put

    
    

    This is a big help. I figured it out by testing and it works for me.

提交回复
热议问题