Codeigniter: Passing data from controller to view
Solution 1
$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>
Solution 2
In simple terms,
$data['a']
in controller becomes $a
in your view. ($data
won't exist in your view, only the index will become available)
e.g.
Controller:
$data['hello']='hellow world';
view:
echo $hello;
Solution 3
You just need to create a array, you using codeigniter right?
Example on controller:
$data['hello'] = "Hello, world";
$this->load->view('results_view', $data);
In de page "results_view" you just have to:
<?php echo $hello;?>
Obs: You can create n datas, just pay attention in the name and make it a array.
Obs²: To use the data use the key of the array with a echo.
Solution 4
The view wouldn't call the data 'data'
The controller would include an associative index (not sure if that's correct nomenclature) for data e.g 'stuff' looking thus $data['stuff']
You'd echo
in the view so: echo $stuff;
not echo $data;
I am a v lowly code fiddler but do really like CodeIgniter so excuse me if i've got this arse about tit.
One more thing - surely your constructor function is a bit of a waste. All that loading of libraries and helpers is done with the autoload file.
Solution 5
You can create property $data = []
; inside CI_Controller(path: system/core/Controller.php) and store all data to show in view. U can load common data like languages, menu, etc in CI_Controller. Also u can add special data for view in controller. (example: $this->data['message'] = "Hello world";
)
Finally, u can pass $this->data
to view when load view (example: $this->load->view('view_name',$this->data);
)
I hope this will help you
Andrew Lynch
A university student pursing a Master Degree in International Relations who is learning to code in Ruby on Rails. Contributor for memeburn.com Entrepreneur @ CableKiosk.co.za
Updated on April 20, 2021Comments
-
Andrew Lynch about 3 years
I want to pass
$data
from the controller namedpoll
to theresults_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>