0
votes

Using Codeigntier 3

I am trying to limit my database content to 5 posts. Right now I have my foreach working correct, but I do not know how to limit the number to 5.

Most of the stuff I found online is from codeigniter 2.

Controller

public function index(){

        $data['Sideposts'] = $this->Blog_Model->get_bposts();

Model

public function get_bposts($slug = FALSE){

if($slug === FALSE){

  $this->db->order_by('date','DESC');
  $query = $this->db->get('blogposts');
  return $query->result_array();
}

View Code

<?php foreach($Sideposts as $Sidepost):{ ?>

                        <ul style="list-none;">

   <?php echo $Sidepost['title']; ?>

                        </ul>

                    <?php }endforeach; ?>
4

4 Answers

1
votes
public function get_bposts($slug = FALSE,$lmt=0){

if($slug === FALSE){

  $this->db->order_by('date','DESC');
  if($lmt>0)
  {
       $query = $this->db->get('blogposts',$lmt);
  } else {
       $query = $this->db->get('blogposts');   
  }
  return $query->result_array();
}

Use it as follow:

$data['Sideposts'] = $this->Blog_Model->get_bposts(FALSE,5);
0
votes

Just replace this in your Model php

  $query = $this->db->get('blogposts');

By

  $query = $this->db->get('blogposts', 5);

https://www.codeigniter.com/userguide3/database/query_builder.html

0
votes

Use camao's answer but add a parameter to the get_bposts() function to specify how many you want to get.

0
votes

I agree with the previous answer, for use you can use parameters like the following:

public function get_bposts ($ slug = FALSE, $ limit = NULL) {
.....
if (isset ($ limit))
  $ query = $ this-> db-> get ('blogposts', $limit);
else
  $ query = $ this-> db-> get ('blogposts');
.....
}

now for certain uses you can add a limit as a parameter.