I am using code igniter and I am building a query to return how many people attended an event. So I can take the number and try to work out a percentage.
The issue I am having is I am trying to build the query according to Codeigniter 3 Docs, But I am returning the wrong result for some reason and simply cannot figure out why.
First of all here is the table in my database I am querying:
Here is the function I am calling from my controller:
public function get_event_attendance_percentage($id) {
$this->db->select('*');
$this->db->from('attendance');
$this->db->where('event_id', $id );
$this->db->where('attended', 1 );
$attendancecount = $this->db->get();
return count($attendancecount);
}
I am selecting all from my attendance table, I am then stating I want all attendance from event with id 17 then I am also stating where attended is = 1
I want to return the number 3 but I am returning number 1.
Can anyone help me see where I am going wrong please?
I got this working with the grateful help of @Vickel. Here is the query that returned the correct result:
public function get_event_attendance_percentage($id) {
$this->db->select('*');
$this->db->from('attendance');
$this->db->where('event_id', $id );
$this->db->where('attended', 1 );
$attendancecount = $this->db->get();
return $attendancecount->num_rows();
}
count()
is a php built-in function, and in the way you use it, it "counts" the query string, therefore returns 1, no matter whatthe correct CI way is to use
return $attendancecount->num_rows()
: see hereIF you want just count number of rows, you can use $this->db->count_all_results() as below.
Check CodeIgniter Manual => https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=count_all#limiting-or-counting-results
NOTE :-
num_rows() :- With num_rows() you first perform the query, and then you can check how many rows you got. Useful when you need table data.
count_all_results() :- With count_all_results() you get the number of rows your query would produce, but doesn't give you the actual resultset. Useful when you need just rows count for i.e. pagination, display no. of records etc.