Caching MySQL queries

10,644

Solution 1

This is a great overview of how to cache queries in MySQL:

Solution 2

You can use Zend Cache to cache results of your queries among other things.

Solution 3

It may be complete overkill for what you're attempting, but have a look at eAccelerator or memcache. If you have queries that will change regularly and queries that won't, you may not want all of your db queries cached for the same length of time by mysql.

Caching engines like the above allow you to decide, on a query-by-query basis, how long the data should be cached for. So say you've data in your header that will change infrequently, you can check if it's currently in the cache - if so, return it, otherwise do the query, and put it into cache with a lifetime of N, so for the next N seconds every page load will pull the data from cache without going near MySQL. You're then free to pull your other data "live" from the db as and when required, by-passing the cache.

Solution 4

I think the query cache size is 0 by default, which is off. Edit your my.cnf file to give it at least a few megabytes. No PHP changes necessary :)

Share:
10,644
Teifion
Author by

Teifion

I am a Software Engineer in a UK Car Insurance provider. I mainly work in Python and PHP.

Updated on June 19, 2022

Comments

  • Teifion
    Teifion almost 2 years

    Is there a simple way to cache MySQL queries in PHP or failing that, is there a small class set that someone has written and made available that will do it? I can cache a whole page but that won't work as some data changes but some do not, I want to cache the part that does not.

  • shgnInc
    shgnInc about 10 years
    As I install mysql on many Ubuntu/Debian servers and checked they re configurations, caching is turn on by default. query_cache_limit=1M and `query_cache_size=16M'