Codeigniter newbie: Count query results? - php

I have my query:
$query = $this->db
->get_where('users', array('group_id' => 7, 'active' => 1));
It works if I use:
print_r ($query->result());
All I want to do, is get the total number of rows that match my query. I've tried num_rows and count(), but I can't get either of them to work!
Any help would be greatly appreciated! At the moment, I am just testing this in my view, but will move it over to my model when I figure it out.
Thanks!!

You need to use $query->num_rows(). It will return total number of rows returned using your query.
for example :
$query = $this->db->query("YOUR QUERY");
if ($query->num_rows() > 0)
{
//DO your stuff
}
For more reference see Documentation.

Try count_all_results
Example:
echo $this->db->count_all_results('my_table');
// Produces an integer, like 25
$this->db->like('title', 'match');
$this->db->from('my_table');
echo $this->db->count_all_results();
// Produces an integer, like 17
OR
echo $this->db->where('group_id',1)->count_all_results('users');

Related

CodeIgniter: How to get the number of records before get all results?

I need to get the number of records for a query before apply a limit. I tried with the following code:
$db = $this->load->database();
$this->db->select($this->select_column)
->from($this->table);
echo $this->db->count_all_results();
But count_all_results don't return any number. If I excecute $this->db->get(), I obtained a result sets, but first I need to apply a limit.
What can be happenning with $this->db->count_all_results()?
Is there another solution for get the count of rows returned based on the previews query?
I'm using Codeigniter 3 with MySQL.
Try doing the the following first to get the count:
$this->db->select('count(*) as ct');
$count = $this->db->get($this->table)->result()[0]->ct;
Now your variable $count has the count you need to apply the limit, so you can
$this->db->.... // Your code
$this->load->database(); // Database is lodaed
$query = $this->db->get('table_name');
return $query->num_rows();
// This will return count of total rows
//After that you can return the result
return $query->result();

extracting a query result in cakephp 3

Hello everyone will see I have the following query
$query = $this->PreguntasAlternativas->find();
$query->select(['id_alternativa' => $query->func()->max('id_alternativa')
])->where(['id_pregunta' => $idquestion]);
This returns me such an arrangement
query(array)
0(object)
id_alternativa(null)
and what I want is to get the value returned me to then do a validation, not how to retrieve the value returned by the query me to do something like
if($query == null){
$result = 1;
}else{
$result = +1;
}
please help
Queries are lazily executed, and as such your query will be a Cake\ORM\Query object. You will need to execute the query in order to be able to process the results.
If you add ->toArray() to your query, this will cause it to be executed and converted to an array. This will allow you to work with the results.
my fues solution this, change the structure of my query
$query = $this->PreguntasAlternativas->find('all', ['conditions' => ['id_pregunta' => $idquestion]]);
$result = $query->max('id_alternativa');
if(!$result['id_alternativa']){
$result['id_alternativa'] = 1;
} else {
$result['id_alternativa'] += 1;
}
Thanks

unable to count the result with a condition using codeigniter query

I am trying to count rows of bookdetails table where display_id is as argument. Say i passed $id='3'. But i am not getting the output.
I think the code which i am trying is wrong. Please help me to write this query correctly
//--- Counting the rows of bookdetails of table where display_id is as argument-------------------------------------------------------------
public function record_count_for_secondtopBooks($id) {
$this->load->database();
return $this->db->count_all("bookdetails",array('display_id'=>$id));
}
count_all returns the number of rows in a particular
echo $this->db->count_all('my_table');
Try this
$this->db->where('display_id', $id);
$this->db->from('bookdetails"');
$this->db->count_all_results();
count_all accepts only one argument and that is table name. So you will get count of all records in that table. as written in manual:
Permits you to determine the number of rows in a particular table.
Submit the table name in the first parameter. Example:
$this->db->where('display_id',$id);
$result = $this->db->count_all("bookdetails");
or Chain em'
$result = $this->db->where('display_id',$id)->count_all("bookdetails");
check:
echo'<pre>';
print_r($result);
echo'</pre>';
Just try this,
$this->db->where('display_id', $id);
$query = $this->db->count_all('bookdetails');
return $query;
please try below code
public function record_count_for_secondtopBooks($id) {
$this->db->where('display_id',$id);
$q = $this->db->get('bookdetails');
return $q->num_rows();
}
try this
public function record_count_with_where($table_name,$column_name,$type)
{
$this->db->select($column_name);
$this->db->where($column_name,$type);
$q=$this->db->get($table_name);
$count=$q->result();
return count($count);
}

Count rows before adding a further limit statement CodeIgniter?

I have ran into a problem...
I have a bunch of where statments like so...
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
Then a limit statement
$this->db->limit($limit, $offset);
And finally my get statement
$query = $this->db->get('table-name');
My problem is I need to count the results before my limit statement, to get the total rows without the limit.. So I tried this..
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
$num_rows = $this->db->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
This counts my rows with the where statements fine.. However, the get statement now gets records without the previous where statements working.
It's not visible, but there is a large amount of code handling more where statements, and grabbing things in urls, So I'd prefer not to perform the retrieval of data twice in order to fix this...
Cheers!
I know this is an old question, but I just ran into this problem and came up with a different solution.
The idea is to take a copy of the db class before the limit and offset.
$this->db->where('Pool', "1");
$this->db->where('Bedrooms >=', "3");
//here we use the clone command to create a shallow copy of the object
$tempdb = clone $this->db;
//now we run the count method on this copy
$num_rows = $tempdb->from('table-name')->count_all_results();
$this->db->limit($limit, $offset);
$query = $this->db->get('table-name');
I know that's an old question but I found a pretty simple solution.
//do your select, from and where
$this->db->select('your selects');
$this->db->from('your table');
$this->db->where('your where');
//get the filtered rows count
//the trick is the first empty parameter and second false parameter
$filtered_count = $this->db->count_all_results('', false);
//limit your results and get the rows
$this->db->limit($length, $start);
$results = $this->db->get()->result_array();
Hope it helps someone
$get_data = $this->your_model->get_data();
$data = $get_data['data'];
$count = $get_data['count'];
Model
function get_data($limit = 10, $offset= 0)
{
$table = 'table-name';
$where = array('Pool' => 1, 'Beedrooms >=' 3);
$return['data'] = $this->db->from($table)->where($where)->limit($limit, $offset)->get();
$return['count'] = $this->db->from($table)->where($where)->count_all_results();
return $return;
}
$this->db->select('*');
$this->db->from('users');
$this->db->where('active',$status);
//open1 here we copy $this->db in to tempdb and apply
//count_all_results() function on to this tempdb
$tempdb = clone $this->db;
$num_results= $tempdb->count_all_results();
// now applying limit and will get actual result
$this->db->limit(10);
$this->db->get();
$query = $this->db->last_query();
$res = $this->db->query($query);
$data_array = array('num_results' => $num_results, 'results' => $res->result() );
return $data_array;
It is quite evident that you would need to use two different queries. It would be optimum to do this as quickly as possible using a single query, but since you need to get all the records before the second query, we need to use two queries.
However, you can optimize the first query based on the engine you use with MySQL. If you use InnoDB then you should use SELECT COUNT(*) FROM <table-name> cause the total row size is cached in InnoDB.
I believe count_all_rows uses count(*) for performance and you should be sorted using this direcctly.
With MyISAM you can use COUNT(<column-name>).
So, you have a count function in your model class which returns the count for your table and then you can call the function to insert/update/get data from your database.
You can use SQL_CALC_FOUND_ROWS of mysql
SELECT SQL_CALC_FOUND_ROWS * FROM table1
WHERE
cond1, cond2, ..., condN
LIMIT 10
SELECT FOUND_ROWS();
This is using mysql, you may need to check how to use it codeignitor way.
Reference:
https://dev.mysql.com/doc/refman/5.7/en/information-functions.html#function_found-rows
I know this question is old but I had the same issue and got a simpler solution than the displayed here. No need to build the query twice and no need to clone the db class. Just count the result without resting the query builder after you add the where part and then you add the limit and execute your query.
$this->db->where('Pool', 1);
$this->db->where('Beedrooms >=' 3);
$count = $this->db->count_all_results('table-name', false); // No reset query builder
$this->db->limit($limit, $offset)
$result = $this->db->get();
You are going to have two variables:
$count with the number of results and $result with the result.

Counting num_rows issue

I have a query like this:
SELECT * FROM configurations WHERE ID = userID
I then have logic like this:
if ($query->num_rows() > 0) {
foreach($query->result() as $row) {
// display data
}
else {
// display no data found message
}
But when I try to do this:
count($query->num_rows())
it is always 1, no matter how many results are returned. If 1 or more are returned the "if" is executed. If there are no results returned the "else" is executed. Yet, the count never changes. What is going on?
You can't count() a number, it works fine. If you only want number of records from table use COUNT() in SQL...
$sql = mysql_query("SELECT COUNT(0) AS count FROM configurations WHERE ID = userID");
$sql = mysql_fetch_assoc($sql);
$count = $sql["count"];
Otherwise just assign $count = $query->num_rows(); as #chriso stated.
Firstly else { should be } else { - you're missing a brace
Secondly, count() is used to count the number of elements in an array. Since $query->num_rows() returns a number rather than an array, you don't need to use count(). In your case, count() was telling you that there's one number, not what the actual number was!
Try:
$count = $query->num_rows();
echo $count;
You're getting an integer with $query->num_rows(), so when you run that integer through the count() function it is designed to return 1.
http://us2.php.net/manual/en/function.count.php
If var is not an array or an object
with implemented Countable interface,
1 will be returned. There is one
exception, if var is NULL, 0 will be
returned.

Categories