CodeIgniter Forums
Running a same query multiple times? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: Best Practices (https://forum.codeigniter.com/forum-12.html)
+--- Thread: Running a same query multiple times? (/thread-71662.html)



Running a same query multiple times? - kaitenz - 09-10-2018

Hi,

Is it OK to run a single query multiple times?

In my profiler, it shows that I ran the same query about 5 times. That query came from my model named "Forms_model" with method name "get_content()"

Now this method Forms_model::get_content() called from different models 8 times minus 3 because it will only be called if the condition (in some part) is TRUE.

Maybe this is a bad practice so I need your advice. Thank you.


RE: Running a same query multiple times? - ignitedcms - 09-10-2018

Obviously if you can do the same thing in one query it is better, but not always practical. I think it depends on your situation or application.


RE: Running a same query multiple times? - Pertti - 09-11-2018

If it's exact same query, you probably ought to try and reuse values. Dependency injection would work quite well for this, or you could implement internal caching just for that model method:

PHP Code:
private $_get_content_cache null;

public function 
get_content()
{
    if (
is_null($this->_get_content_cache)) {
        
$q $this->db->get(...);
        
$this->_get_content_cache $q->result();
    }
    return 
$this->_get_content_cache;




RE: Running a same query multiple times? - php_rocs - 09-11-2018

@kaitenz,

Try to avoid running a query multiple times (for a single page/controller) it is not efficient. You definitely have options (such as the ones mentioned above) or session variables or flashdata variables or arrays with multiple variable values.


RE: Running a same query multiple times? - kaitenz - 09-11-2018

To refresh the cache if I will use AJAX, I'll just add either a parameter from get_content($refresh = FALSE) method or a new function called refresh_content_cache()


RE: Running a same query multiple times? - kaitenz - 09-12-2018

Another question guys.

I want to create a query that will select ALL the rows from a database table and put/cache the result to an array property (<- is this correct?).
Then when I need a specific row, instead of running the query, I'll just pull it out from that array (the keys would be the rowId).

Is this OK?  Huh

Let's say I have 2,000+ rows in my table. Is it bad to put all 2,000+ rows in a single variable/property?


RE: Running a same query multiple times? - php_rocs - 09-13-2018

@kaitenz,

This might be helpful... https://www.codeigniter.com/user_guide/database/query_builder.html?highlight=query%20cache#query-builder-caching