[eluser]mikeymayhem[/eluser]
Hi Im fairly new to php and CI in general and have been having some trouble with some code i have been writing on wondered if anybody could help me out a little.
I ventured into php and CI after an idea for a website came to me a few months ago. I have managed to achieve all the features i want on a basic level and have now began trying to improve the functionality of the website a little.
part of the website runs a news section which allows registered users to post comments. Bascially im trying to pull 2 comments from the database to be displayed with its relative news post within a foreach loop. heres how i went about it
Controller
Code:
function index() {
$get_posts = $this->site_model->get_posts();
//fetch new comments an assign to comments key in the posts array
foreach($get_posts->result_array() as $key => $post){
$posts['key'] = $post;
$posts['key']['comments'] = $this->site_model->get_comments($post['id']);
}
$data['get_posts'] = $posts;
//load the view
$data['main_content'] = 'site/site_view';
$this->load->view('includes/template',$data);
}
}
Code:
The Model:
function get_posts() {
$this->db->where('active', '1');
$this->db->order_by('post_date','desc');
return $this->db->get('news');
}
function get_comments($id) {
$this->db->where('news_id', $id);
$this->db->where('active', '1');
$this->db->order_by('post_date','desc');
$this->db->limit('2');
return $this->db->get('news_comments');
}
Code:
The View:
<?php foreach($get_posts as $post):?>
<p><?php echo $post['id']; ?></p>
<p> <?php echo $post['title']; ?></p>
<?php foreach($post['comments']->result_array() as $comment): ?>
<p><?php echo $comment['id'];?></p>
<p><?php echo $comment['user_id'] ?></p>
<?php endforeach; ?>
<?php endforeach; ?>
This only seems to pull one result from the news table when there are several in there. Any help or suggestions would be greatly apprciated
Thanks in advance