Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Best way to cache MySQL results?

I am currently building a PHP framework (original, i know) and im working on some optimisation features for it. One dilema I have come accross is what is the best way to cache MySQL results? I know some people will say, first optimise your MySQL etc, but lets say for arguments sake, my query takes 1 minute to run and is as optimised as possible.

What would be the best way to cache the results in PHP so I dont have to rerun the query every page load?

My first thought was to maybe loop through the results, add them to an array... serialize them and then store in a file. Now as creating the cache only occurs once, I can afford the overhead of the serialize function if the array contains say 1 million results. How ever, loading the cached file and then unserializing the array on every pageload, could have performance impact.

Would it then be a better idea to while caching, instead of serializing the results and the writing to file, write to the file in a way that displays the results in a PHP readable array. So when it loads, there is no unserialize overhead.

Are there any other (read: faster) ways to cache a slow query for frequent use?

like image 847
Ozzy Avatar asked Mar 16 '11 15:03

Ozzy


People also ask

How do I cache MySQL results?

MySQL determines the queries to cache by examining the query_cache_type variable. Setting this value to 0 or OFF prevents caching or retrieval of cached queries. You can also set it to 1 to enable caching for all queries except for ones beginning with the SELECT SQL_NO_CACHE statement.

Can I use Redis with MySQL?

Redis is an open-source and in-memory data structure store that can be used for caching, real-time analytics, searching, and machine learning. Integrate Redis with PHP and MySQL will improve your application performance because Redis stores data in RAM. You can use it with databases like MySQL or MariaDB.

Can PHP be cached?

PHP basically has two main types of caching: 'output caching' and 'parser caching'. PHP 'output caching' saves a chunk of data somewhere that can later be read by another script faster than it can generate it. 'Parser caching' is specific feature.


1 Answers

If this is a straight array, then you could use var_export() rather than serialize (wrapping it with the appropriate "" and write it to a .php file; then include() that in your script. Best done if you can write it outside the htdocs tree, and only really appropriate for large volumes of data that memory caches would consider excessive.

like image 167
Mark Baker Avatar answered Oct 02 '22 11:10

Mark Baker