Grig Dodon
Grig Dodon

Reputation: 63

CodeIgniter pagination. Total rows

I have this problem and i can't find what is wrong. So, my Controller:

$config = array();
$config["base_url"] = base_url() . "products/page/";
$config["total_rows"] = count($this->model_add->countProducts());
$config["per_page"] = 12;
$config["uri_segment"] = 4;
$config["num_links"] = 2;
$config["use_page_numbers"] = true; 

model:

public function countProducts() {
    $query = $this->db->query("SELECT * FROM `tdt_articles` WHERE `deleted` = 0 AND `article_type` = 3");
    return $query->result();
}

My problem is that in my webpage, it shows less pages that it should show. If on $config["total_rows"] i put exact number of records it shows well, but if i count them like is showed there, it doesn't show me all of them. Can't understand at all what is the problem. Hope you'll help me! Thanks!!!

Upvotes: 0

Views: 4670

Answers (3)

uellingtonpalma
uellingtonpalma

Reputation: 33

controller:

$total_rows = $this->model_add->countresults()->num_rows();

$config = array();
$config["base_url"] = base_url() . "products/page/";
$config["total_rows"] = $total_rows;
$config["per_page"] = 12;
$config["uri_segment"] = 4;
$config["num_links"] = 2;
$config["use_page_numbers"] = true; 

model:

function countresults() {

      $this->db->select('*');
      $this->db->from($this->table);

      return $this->db->get();

    }

Upvotes: 0

Phil Cross
Phil Cross

Reputation: 9302

You're returning an object of data rather than the actual int number of rows. Change your model method to this:

public function countProducts() 
{
    $query = $this->db->query("SELECT * FROM `tdt_articles` WHERE `deleted` = 0 AND `article_type` = 3");
    return $query->num_rows();
}

Alternatively, you can build your querying using active record:

public function countProducts()
{
    $result = $this->db->from('tdt_articles')
                       ->where('deleted', 0)
                       ->where('article_type', 3)
                       ->get();

    return $result->num_rows();
}

You need to use the num_rows() method to get the number of records in a result.

  • result_array() returns a multidimensional array of results.
  • row_array() returns a single-dimensional array of results - for one record
  • results() returns a stdClass object
  • num_rows() returns an integer, which specifies the number of records returned by the database.

Upvotes: 1

Raphioly-San
Raphioly-San

Reputation: 404

public function countProducts() {
    $query = $this->db->query("SELECT * FROM `tdt_articles` WHERE `deleted` = 0 AND `article_type` = 3");
    return $query->result();
}

Shouldn't the select clause read:

SELECT count(id) as record_count

The method/function should return the output of record_count.

[edit] Now you don't need to do a count(...) afterward. Plus you let the DB handle it, which is faster than letting php handle it. [/edit]

Upvotes: 0

Related Questions