codeigniter count_all_results - codeigniter

I'm working with the latest codeIgniter released, and i'm also working with jquery datatables from datatables.net
I've written this function: https://gist.github.com/4478424 which, as is works fine. Except when I filter by using the text box typing something in. The filter itself happens, but my count is completely off.
I tried to add in $res = $this->db->count_all_results() before my get, and it stops the get from working at all. What I need to accomplish, if ($data['sSearch'] != '') then to utilize the entire query without the limit to see how many total rows with the search filter exists.
If you need to see any other code other than whats in my gist, just ask and I will go ahead and post it.

$this->db->count_all_results() replaces $this->db->get() in a database call.
I.E. you can call either count_all_results() or get(), but not both.
You need to do two seperate active record calls. One to assign the results #, and one to get the actual results.
Something like this for the count:
$this->db->select('id');
$this->db->from('table');
$this->db->where($your_conditions);
$num_results = $this->db->count_all_results();
And for the actual query (which you should already have):
$this->db->select($your_columns);
$this->db->from('table');
$this->db->where($your_conditions);
$this->db->limit($limit);
$query = $this->db->get();

Have you read up on https://www.codeigniter.com/userguide2/database/active_record.html#caching ?
I see you are trying to do some pagination where you need the "real" total results and at the same time limiting.
This is my practice in most of my codes I do in CI.
$this->db->start_cache();
// All your conditions without limit
$this->db->from();
$this->db->where(); // and etc...
$this->db->stop_cache();
$total_rows = $this->db->count_all_results(); // This will get the real total rows
// Limit the rows now so to return per page result
$this->db->limit($per_page, $offset);
$result = $this->db->get();
return array(
'total_rows' => $total_rows,
'result' => $result,
); // Return this back to the controller.
I typed the codes above without testing but it should work something like this. I do this in all of my projects.

You dont actually have to have the from either, you can include the table name in the count_all_results like so.
$this->db->count_all_results('table_name');

Count first with no_reset_flag.
$this->db->count_all_results('', FALSE);
$rows = $this->db->get()->result_array();
system/database/DB_query_builder.php
public function count_all_results($table = '', $reset = TRUE) { ... }

The
$this->db->count_all_results();
actually replaces the:
$this->db->get();
So you can't actually have both.
If you want to do have both get and to calculate the num rows at the same query you can easily do this:
$this->db->from(....);
$this->db->where(....);
$db_results = $this->get();
$results = $db_results->result();
$num_rows = $db_results->num_rows();

Try this
/**
* #param $column_name : Use In Choosing Column name
* #param $where : Use In Condition Statement
* #param $table_name : Name of Database Table
* Description : Count all results
*/
function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
$this->db->select($column_name);
// If Where is not NULL
if(!empty($where) && count($where) > 0 )
{
$this->db->where($where);
}
// Return Count Column
return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}
Then Simple Call the Method
Like this
$this->my_model->count_all_results(['column_name'],['where'],['table name']);

If your queries contain a group by, using count_all_results fails. I wrote a simple method to work around this. The key to preventing writing your queries twice is to put them all inside a private method that can be called twice. Here is some sample code:
class Report extends CI_Model {
...
public function get($page=0){
$this->_complex_query();
$this->db->limit($this->results_per_page, $page*$this->results_per_page);
$sales = $this->db->get()->result(); //no table needed in get()
$this->_complex_query();
$num_results = $this->_count_results();
$num_pages = ceil($num_results/$this->results_per_page);
//return data to your controller
}
private function _complex_query(){
$this->db->where('a', $value);
$this->db->join('(subquery) as s', 's.id = table.s_id');
$this->db->group_by('table.column_a');
$this->db->from('table'); //crucial - we specify all tables here
}
private function _count_results(){
$query = $this->db->get_compiled_select();
$count_query = "SELECT count(*) as num_rows FROM (".$query.") count_wrap";
$r = $this->db->query($count_query)->row();
return $r->num_rows;
}
}

Related

how can i increment 6 months selecting from database to_date field?

I'm making my project,and want to increment date from fetching to_date filed with 6 months if last to_date is gone then add more 6 months and so on what can i do for this?
$abc=(Session::get('email'));
$email= $request->input('email');
if (Maintenance::where('email', '=', $email)) {
$users=Carbon::create(2019,0,30)->addMonths(6)->toDatestring();
if (Maintenance::where('maintenance_status', '=', 'PAID')->orderBy('todate','DESC')) {
$check = Maintenance::select('to_date')->where('maintenance_status', '=', 'PAID')->orderBy('to_date','DESC')->get();
// $users= Carbon($check[0])->addmoths(6);
$users = Carbon::addMonths(6)->toDatestring();
i expect the output of 30-06-2019,30-12-2019 and so on but the actual output is only increment one time using Carbon and i want to increment fetching from database date
It looks like you are overwriting your variable instead of adding to it.
$users = Carbon\Carbon::create(2019,0,30)->addMonths(6)->toDatestring();
returns 2019-06-30.
$users = Carbon\Carbon::addMonths(6)->toDatestring(); would overwrite it, but it actually breaks "PHP Error: Call to a member function addMonths() on string".
Don't store the string as your variable. Instead, keep it as a instance of Carbon so that you can call functions on it. Then when you need to use it call toDatestring().
It would look something like this:
$date_to_increment = Carbon\Carbon::create(2019,0,30)->addMonths(6);
echo($date_to_increment->toDatestring()); // 2019-06-30
if ($your_condition) {
$date_to_increment->addMonths(6);
echo($date_to_increment->toDatestring()); // 2019-12-30
}
As far as applying it to your case, there are a few issues. Your first condition is invalid. I believe it will always return true as you never execute the query. I'm also assuming since you are matching an email that there will only be one result. So lets use the query builder method first() to save a step as this will return a single entry instead of an array.
$maintenance = Maintenance::where('email', '=', $email)->first();
if ($maintenance) {
// do stuff
}
Then you have a few more conditions that have similar issues, but more importantly, they are re-querying so you are losing the restrictions in your collection each time.
Instead:
$maintenance = Maintenance::where('email', '=', $email)->first();
if ($maintenance) {
if ($maintenance->maintenance_status === 'PAID') {
// do something
}
}
Finally, to use the value from the database:
if ($maintenance->maintenance_status === 'PAID') {
$date = Carbon\Carbon::parse($maintenance->to_date)->addMonths(6);
$maintenance>to_date = $date->toDatestring();
$maintenance->save();
}

Laravel controller and adding to the result set

I've checked the Q&A about this and can't find anything, so thought i'd ask.
I have a very simple Laravel controller returning all results from a table as below via the 'Name model'. There is then also a further call to my controller, via the model to count the rows and all works and sends to the result set fine...
// All results from my 'Name' model:
$results = $this->name->getAllResults(); // All works fine.
// I then use my controller again, count the rows via the model and add them to $results:
$results['count'] = $this->countNames(); // Again fine
BUT, when i try to add a string to the $results array before i pass it off to th view, as in:
$results['test'] = 'Test'; // This fails in the view
$results['test'] = 124; // But this passes in the view and renders.
It only seems to allow me to add an INT to my result set array. as $results['test'] = 124 also fails.
I then finally, have this sending to my view via:
return view('names', compact('results')); // And that works fine.
Can anyone see what it is I am missing and why integer added to $results works and not a string?. Many thanks in advance.
You are updating collection data. The following line will give collection of models.
$results = $this->name->getAllResults(); // This may give collection of the model
And below, you are updating the collection object.
$results['count'] = $this->countNames();
You can do the following to safely send data to view, without modifying any.
$results = $this->name->getAllResults();
$count = $this->countNames();
$test = 'Test';
$test2 = 124;
return view('names', compact('results','count','test','test2'));

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

How to increment a column using Eloquent Model in Laravel 4

I am not sure how to increment the value in a column using Eloquent Model in Laravel 4?
This is what I currently have and I am not sure how correct is this.
$visitor = Visitor::where('token','=','sometoken')->first();
if(isset($visitor)){
$visitor->increment('totalvisits');
}else{
Visitor::create(array(
'token'=>'sometoken',
'totalvisits'=>0
));
}
With Query Builder we could do it using
DB::table('visitors')->increment('totalvisits');
Looks like the code that I posted worked after all
$visitor = Visitor::where('token','=','sometoken')->first();
if(isset($visitor)){
$visitor->increment('totalvisits');
}else{
Visitor::create(array(
'token'=>'sometoken',
'totalvisits'=>0
));
}
Prior to a fix a few weeks ago the increment method actually fell through to the query builder and would be called on the entire table, which was undesirable.
Now calling increment or decrement on a model instance will perform the operation only on that model instance.
Laravel 5 now has atomic increment:
public function increment($column, $amount = 1, array $extra = [])
{
if (! is_numeric($amount)) {
throw new InvalidArgumentException('Non-numeric value passed to increment method.');
}
$wrapped = $this->grammar->wrap($column);
$columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
return $this->update($columns);
}
which essentially works like:
Customer::query()
->where('id', $customer_id)
->update([
'loyalty_points' => DB::raw('loyalty_points + 1')
]);
Below is old answer for Laravel 4 where the built-in increment was a seperate select and then update which of course leads to bugs with multiple users:
If you'd like to accurately count your visitors by ensuring the update is atomic then try putting this in your Visitor model:
public function incrementTotalVisits(){
// increment regardless of the current value in this model.
$this->where('id', $this->id)->update(['totalVisits' => DB::raw('last_insert_id(totalVisits + 1)')]);
//update this model incase we would like to use it.
$this->totalVisits = DB::getPdo()->lastInsertId();
//remove from dirty list to prevent any saves overwriting the newer database value.
$this->syncOriginalAttribute('totalVisits');
//return it because why not
return $this->totalVisits;
}
I'm using it for a change tag system but might work for your needs too.
Does anyone know what to replace the "$this->where('id',$this->id)" with because since dealing with $this Visitor it should be redundant.

how to combine results of query and return that result using codeigniter

i am new with codeigniter.
i have used the following code to execute query recursively.
Suppose $q query select 4 id (10,11,20,24)
then for each id showreply function (in foreach) call recursively then how can return the combine result.
$resultq3 = $this->showreply($reply_id);
<?php
public function showreply($reply_id)
{
$q1 =$this->db->select('*')
->from('forum_reply AS fr')
->where('fr.parent_id',$reply_id1)
->order_by('fr.id ')->get();;
foreach($q1->result_array() as $row4)
{
$id = $row4['id'];
$parent_id = $row4['parent_id'];
if($parent_id!=0)
{
$this->showreply($id);
}
}
return $result;
}
?>
I'm not really understanding what it is you're asking here. Maybe showing the showReply function would help, but you already have the combined result and are splitting that out in your foreach so what's the problem? Also why are you assigning reply_id to reply_id1? What is the point of that? Just use $reply_id in your query.
You're also executing an if statement that makes little sense since you can filter out the id's you don't want in the query itself (and are you seriously ever going to have an id that = 0?)
In fact the more I look at this code the more confused I become. Where is $id getting populated for $this->showreply($id)?
<?php
public function showreply($reply_id)
{
$q1 =$this->db->select('*')
->from('forum_reply AS fr')
->where('fr.parent_id',$reply_id)
->where('fr.parent_id !=',0)
->order_by('fr.id ')->get();;
//$i=0;
foreach($q1->result_array() as $row4)
{
$parent_id = $row4['parent_id'];
$this->showreply($id);
}
//below is the actual answer to your question on how to return the combined results.
return $q1->result_array();
}
?>
Okay after rereading your question I think I have a better understanding. If you pass the id's as an array like this:
$reply_id = array(10,11,20,24);
You can then modify your query to use:
$this->db->where_in('fr.parent_id', $reply_id);
That will return the results as one combined result with all 4 ids included.

Resources