How would I call a controller inside the view? When I use the code below, I'm limited with Html and CSS formatting. I could use jQuery JSON, but that's added work. Any ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function displayList() {
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
echo $row->title . "<br>";
echo $row->text;
}
}
function index() {
$this->load->view('home');
$data['lists'] = $this->displayList();
}
}
?>
You don't call the controller in the view. You pass the data from the controller to the view.
Like this:
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
Now in your home
view, $lists
will be the value of displayList()
.
Also, displayList
is echo
ing out the data, not returning it so $data['lists']
will be blank. You should return
the string, so the view can echo
it.
function displayList() {
$str = ''
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$str .= $row->title . "<br>" . $row->text;
}
return $str;
}
P.S. I usually put DB queries into a model, and have the controller call them.
You'll send an array of the stuff you want as the second argument to the load->view
$data['lists'] = $this->displayList();
$this->load->view('home',$data);
Now, you can access it in the view by using $lists
.
I think what you're trying to do is this...
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function displayList() {
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
echo $row->title . "<br>";
echo $row->text;
}
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home',$data);
}
}
?>
then you can use $lists
in the view to access that data