Saturday, 18 November 2017

codeigniter count_all_results

codeigniter count_all_results


Sol 1: 

$this->db->count_all_results() replaces $this->db->get() in a database call.
I.E. you can call either count_all_results() or get(), but not both.
You need to do two seperate active record calls. One to assign the results #, and one to get the actual results.
Something like this for the count:

ContentMiddleAd

$this->db->select('id');
$this->db->from('table');
$this->db->where($your_conditions);
$num_results = $this->db->count_all_results();
And for the actual query (which you should already have):
$this->db->select($your_columns);
$this->db->from('table');
$this->db->where($your_conditions);
$this->db->limit($limit);
$query = $this->db->get();

ContentMiddleAd



Sol 2:


I see you are trying to do some pagination where you need the "real" total results and at the same time limiting.
This is my practice in most of my codes I do in CI.
    $this->db->start_cache();

    // All your conditions without limit
    $this->db->from();
    $this->db->where(); // and etc...
    $this->db->stop_cache();

    $total_rows = $this->db->count_all_results(); // This will get the real total rows

    // Limit the rows now so to return per page result
    $this->db->limit($per_page, $offset);
    $result = $this->db->get();

    return array(
        'total_rows' => $total_rows,
        'result'     => $result,
    ); // Return this back to the controller.

ContentMiddleAd

I typed the codes above without testing but it should work something like this. I do this in all of my projects.
Sol 3:
The
$this->db->count_all_results();
actually replaces the:
$this->db->get();
So you can't actually have both.
If you want to do have both get and to calculate the num rows at the same query you can easily do this:
$this->db->from(....);
$this->db->where(....);
$db_results = $this->get();

$results = $db_results->result();
$num_rows = $db_results->num_rows();

Sol 4:
$this->db->count_all_results('PM_ADMIN_LIST');
is returning the number of rows in the table and ignorning the restrictors above it.
Try:-
$this->db->where('username',$username);
$this->db->where('password',$password);
$this->db->from('PM_ADMIN_LIST');
$count = $this->db->count_all_results();
Also, put some debug in - if you knew what the value of $count was then it may have helped you work out that the Active Record query was wrong rather than thinking it was doing an OR instead of an AND.






No comments:

Post a Comment