Welcome Guest, Not a member yet? Register   Sign In
Count results
#1

[eluser]cybersven[/eluser]
I would like to count results from a table where results have a specific category ('A', 'B', 'C', ....).
I've tried this in my model :

Code:
public function count_products($cat)
    {
     $query = $this->db->get_where("data", array('categorie'=>$cat));
     $total = count($query);
     return $total;
    }

When I try to echo the result in the view :
Code:
$this->Products_model->count_products('A');
it says : 1
and there are 4 results actually in my test...

Need help Smile thx in advance
#2

[eluser]Massaki[/eluser]
Code:
$total = $query->num_rows();
#3

[eluser]jonez[/eluser]
If you aren't using the record data for anything using a count query is a lot faster then counting the resulting recordset.

Code:
public function count_products( $category ) {
$sql = "SELECT COUNT(d.id) AS total FROM data d WHERE d.categorie = ?";
$params = array( $category );

$result = $this->db->query( $sql, $params )->row_array( );
$result = (int)$result[ 'total' ];

return $result;
}
#4

[eluser]cybersven[/eluser]
It works like a charm thank you all
#5

[eluser]InsiteFX[/eluser]
Code:
// -----------------------------------------------------------------------

/**
  * count_all_where ()
  *
  * Returns the count of all where clause database records.
  *
  * USAGE:
  *
  * $where = array('id' => $id);
  * or
  * _count_all_where(array('id' => $id));
  *
  * @access public
  * @param string
  * @return mixed
  */
public function count_all_where($where)
{
  $this->db->where($where);
  $query = $this->db->get($this->table);

  return $query->num_rows();
}

// -----------------------------------------------------------------------

/**
  * count_all_get_where ()
  *
  * Returns the count of all where clause database records.
  *
  * USAGE:
  *
  * $where = array('id' => $id);
  * or
  * count_all_get_where($this->table, $where, $limit, $offset);
  *
  * @access public
  * @param string
  * @return mixed
  */
    public function count_all_get_where($where)
    {
        $query = $this->db->get_where($this->table, $where, $limit, $offset);
        
        return $query->num_rows();
    }




Theme © iAndrew 2016 - Forum software by © MyBB