2

How can I write the following SQL using CodeIgniter's query builder methods?

SELECT COUNT(*) AS total
FROM comments
WHERE `level`= 4
2
  • This one is asking how to make a cake, whereas the other one is asking why the cake is too much baked, and all the answers are cooking lessons for the cake. Anyway, this question was valid 12 years ago, and nowadays, the validity of PHP itself is a concern. And you will find no one that will be able to find similarities or differences between the two threads. (exaggerating, of course) Commented Mar 26 at 18:58
  • I am sorry that the system's automated comment seemed to invite you to challenge my nominated dupe target. I am very confident that this question is fully covered by the earlier posted page. My goal is to relate redundant content on Stack Overflow on subjects where I am fairly confident. I don't mean to bother you personally. Commented Mar 26 at 20:04

5 Answers 5

7
$this->db->select('count(*)');
$this->db->from('comments');
$this->db->where('level','4');
$query = $this->db->get();
echo $query->num_rows();
Sign up to request clarification or add additional context in comments.

2 Comments

I think, this will only give 0 or 1 I think, but I got the the way you think. If this is the case, I will edit it.
$query->num_rows() will return number of rows. then you shouldn't use $this->db->select('count()');. It should be $this->db->select('');
5
    $this->db->select('count(*) as total');  
    $this->db->from('comments');
    $this->db->where('level', 4);
    $sql   = $this->db->return_query();
    /*debug*/ 
    /*echo 'sql:: '.$sql;*/
    $query = $this->db->get(); 
    $arr   = $query->row_array(); 
    $total = $arr['total'];  

Comments

2
$query = $this->db->query("SELECT COUNT(*) AS total FROM comments WHERE `level`= 4");
echo $query->result_array();

OR

$this->db->query("SELECT COUNT(*) AS total FROM comments");
$this->db->where("`level`= 4");

1 Comment

I know that but isnt there something similar to $this->db->where(), because I will have lots of $this->db->where() statements.
1

You could always use

$this->db->query('SELECT COUNT( * ) AS total FROM comments WHERE `level`= 4');

3 Comments

I know that but isnt there something similar to $this->db->where(), because I will have lots of $this->db->where() statements.
@bluebrain: there is, but why do you need the CI-specific way? The general mysql access method is shorter and possibly more clear.
So what is the actual type of the query function? a numeric value?
1

I think you'll like similar like this:

$count = $this->db->where("level","4")->count_all_results("comments");

http://codeigniter.com/user_guide/database/active_record.html

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.