CodeIgniter Forums

Full Version: count all result from a table using where clause
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

[eluser]ibnclaudius[/eluser]
I know how to do it using num_rows(), but how can I do this using count_all()?

I tried this, but no success:

Code:
public function count_school_update_comments($update_id)
{
  $query = $this->db->count_all($this->school_updates_comments_table)
    ->where("update_id", $update_id);

  return $query;
}

El Forum

[eluser]ibnclaudius[/eluser]
I was checking the docs. Is that possible? Or only with num_rows()? I want to do it with count_all because I think will use less memory than num_rows(), because with one I just count, and the other I select everything and then count..

El Forum

[eluser]CroNiX[/eluser]
Either way, it still has to query the database and count the results. Do both ways and run the profiler and see which is more efficient. Not sure if you can use a where() with count_all_results(). Check the code for count_all_results(). Its doing a COUNT(field) and returning the num_rows().

El Forum

[eluser]aquary[/eluser]
As long as the the condition are good, using DB's count() is always faster than PHP's count() or CI's num_rows(), which require the data to be sent back to PHP for counting.

And you are putting a wrong code/order. The where should be in front of/before the counting part. The way you did would be... "count everything, then assign a condition for the next query" ?

Code:
$this->db
   ->where('condition', 'value')
   ->count_all_results('table');