Codeigniter: Passing data from controller to view

Andrew Lynch picture Andrew Lynch · Feb 25, 2012 · Viewed 154.5k times · Source

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

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

class Poll extends CI_Controller {

    public function __construct()
       {
            parent::__construct();
            $this->load->database();
            $this->load->helper('form');
       }

    public function index()
    {

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

    public function vote()
    {
        echo "Voting Successfull";
        $this->db->insert('votes',$_POST);
    }

    public function results()
    {
        echo "These are the results";
        //$query = $this->db->get('votes');
        $data = "hello";
        $this->load->view('results_view', $data);

    }
}

Results_view.php

<html>
<?php echo $data; ?>
</html>

Answer

Lawrence Cherone picture Lawrence Cherone · Feb 25, 2012

$data should be an array or an object: http://codeigniter.com/user_guide/general/views.html

$data = array(
    'title' => 'My Title',
    'heading' => 'My Heading',
    'message' => 'My Message'
);

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

results_view.php

<html>
<?php 
//Access them like so
echo $title.$heading.$message; ?>
</html>