Reputation: 608
I am learning CI with an older tutorial (they're using 1.7) so maybe that is the problem.
I have this as my model:
class Site_model extends CI_Model {
function getAll() {
$q = $this->db->get('test');
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data['records'] = $row;
}
return $data;
}
}
}
and this as the controller
class Site extends CI_Controller {
function index() {
$this->load->model('site_model');
$data['records'] = $this->site_model->getAll();
$this->load->view('home', $data);
}
}
But the view file returns only 1 result, instead of all results as in the video.
What needs changing?
Upvotes: 0
Views: 209
Reputation: 4079
I will change your model in this form. It is more clear!
Model:
class Site_model extends CI_Model {
function getAll() {
return $this->db->get('test')->result_array();
}
}
Controller:
class Site extends CI_Controller {
function index() {
$this->load->model('site_model');
$data['records'] = $this->site_model->getAll();
$this->load->view('home', $data);
}
}
View:
<html>
<head></head>
<body>
<?php foreach($records as $r):
echo $r['column_name']; // name of table column
endforeach; ?>
</body
</html>
Upvotes: 2
Reputation: 1869
I suggest using this extension of the ci model class. http://github.com/jamierumbelow/codeigniter-base-model
It is very useful, full of very good functions that you will use over and over.
The one you will want for this lib is get();
Upvotes: 0
Reputation: 28753
Try like
function getAll() {
$q = $this->db->get('test');
if ($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data['records'][] = $row; //Here you need to give an array
}
return $data;
}
}
You are assigning all values to an variable so it is holding only one row data.You need to keep an array to catch all the data rows and pass the array to the controller and then to the view
while we give as $data[] it will treat $data as an array and it will assign variables like $data[0],[1],[2]...like that....if we give $data only then it will treat as variable and it only take one variable or value at once.
Upvotes: 1