• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
problem in calculating count

[eluser]Bigil Michael[/eluser]
i want to count the no: of distinct items in table

i used query like this
function get_total()
        $this->db->select('COUNT(id) AS total');
        $result_total = $this->db->get('cities');
            $row    = $result_total->row();
            $count    =    $row->total;
        return $count;
but it willnot show the correct result....
can any one help me
thanks in advance....

function get_total() {
    $query = $this->db->select('city_name')->distinct()->get('cities');
    if($query !== FALSE) {
        return $query->num_rows();

    return FALSE;

$this->db->select('COUNT("id") AS total');


Try this.

function get_total()

        $total = $this->db
            return $total;
        return 0;
Don't know if its going to work but give it a try, the count all statement will return an int.

OK now I remember i found one of my old applications, your not getting a wrong total what you're doing is counting the amount of cities in each group, because of the distinct function.

So if you do a var_dump youll have something like

New York -> 10
Los Angeles -> 5
San Francisco -> 7

so your code is actually doing what it suppose to but because of the group by your getting this.

So you can try the code at the beginning but here is the question what total do you want?

The total of unique cities.
The total of all cities including duplicates.

The code above may give you the total of unique cities.

You can also return the array instead of just one row and use the php count() function on the array that will give you a total of the unique cities.

Last if you want everything including duplicates then you do count_all() function from CI.

More info here.

[eluser]Bigil Michael[/eluser]

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2020 MyBB Group.