Khirad Zahra
Khirad Zahra

Reputation: 893

How to count total no of records based on value using codiegniter

  id | name | status

   1 |  name | yes

   2 |  name | no 

   3 |  name | yes

How i can count total status with value yes and with value no using active records ? Like count is : yes = 2 , no = 1

This is what i have tried so far

$this->db->select('count(status));
//$this->db->select('count(where status == 'yes')); // not working
$query = $this->db->get();

Upvotes: 1

Views: 38

Answers (3)

ivanavitdev
ivanavitdev

Reputation: 2888

Simply group by then count.

    $sql = "
        SELECT
            status,
            count(*) as count
        FROM
            TABLENAME
        GROUP BY
            status
    ";

    $query = $this->db->query($sql);
    return $query->result();

Upvotes: 1

B. Desai
B. Desai

Reputation: 16436

Use where method of CI to add where condition.change your query like below:

$this->db->select('count(status)');
$this->db->where('status','yes'); // apply where
$query = $this->db->get();

To get all status count, use group by clause

$this->db->select('status,count(status)');
$this->db->group_by('status'); // apply group by
$query = $this->db->get();

Upvotes: 2

N. francis
N. francis

Reputation: 75

Try this

$this->db->select('*');
        $this->db->from('yourtablename');
        $this->db->where("(status = 'yes' AND id = '2' )", NULL, FALSE);
        $query = $this->db->get();

        return $query->num_rows();

Upvotes: 1

Related Questions