I’m trying to display query’s results in my view in different divs, I’ve spend the day reading on ellislab how to display results if I have understand correctly result() function return an object, this is my model:
model
function get_post(){
$this->db->select(*);
$this->db->order_by('date_time', 'desc');
$this->db->limit(2);
$results = $this->db->get('post');
if($results->num_rows()<1){
return false;
}
else{
return $results->result();
}
}
And this is what my controller does:
controller
foreach($results as $res){
$data['post_signature'] = $res->signature;
$data['post_title'] = $res->title;
$data['post_article'] = $res->article;
$data['post_date'] = date('d-M-Y', strtotime($res->date_time));
$data['post_time'] = date('H:i', strtotime($res->date_time));
}
What i would like to show in my view is the series of results in a div and the second in another div.
<div id="1">First Result</div>
<div id="2">Second Result</div>
What I tought to do was to pass the whole query result to the view and use a foreach, like this:
<?php foreach ($results as $res)
<div id="1">First Result</div>
<div id="2">Second Result</div>
?>
Obviously the problem to this approach is that this foreach just reduplicate both the divs and I just want to put the first result in the first div and the second in the second div. I also tought about changing the foreach into the controller and use a for statement to save all the parameters returned into the data array, but for some reasons this seems very inefficient.
I hope you have better solutions.
You should pass your
$resultsobject to the view and use aforeachthere:The idea is that
$resultsis a collection of result objects, so when you loop through them in the controller (like your example in the question) – you’re not getting the “collection” of objects in the view. Looping through the view allows you to manage the collection (and also the display) of those results.