Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Is it good practice to cache MYSQL queries in a txt file?

I'm building an online shop & trying to improve performance by minimising MYSQL queries.

Is it good practice to cache the mysql queries via a txt file and then fetch that instead of the query? This is what I'm doing"

  1. A php class takes the sql query as a string
  2. does an md5 of it
  3. if this is the first time it's run
  4. then perform the query on the database
  5. get the results in an array
  6. serialize the array and store it as md5_Of_Query.txt
  7. return either unserialize(file_get_contents(md5_of_Query.txt)) or $results of actual query, depending on whether or not the cache exists and is valid.
  8. The class also checks the filemtime() of the txt file and if its greater than say, one hour old, then re-perform the query and refresh the cache.

Is this more efficient than doing sql queries every time? Any security issues I'm missing?

like image 607
Emmanuel Avatar asked Jun 22 '11 00:06

Emmanuel


2 Answers

If you do a benchmark, the costs of doing creating a unique hash and performing IO to disk will be greater than simply fetching from the MySQL server.

IMHO, don't bother going to the extent. Good thoughts, but MySQL already has internal caching and performance tweak.

Focus on building your application, as "premature optimization is the root of all evil".

like image 111
mauris Avatar answered Oct 05 '22 23:10

mauris


If you're just starting the application, memcache is a much faster way to go than using text files.

http://memcached.org/

Text files will do the job, and the steps you've outlined make sense, but memcache will be faster and handle a lot of the heavy lifting for you.

like image 23
serialworm Avatar answered Oct 05 '22 23:10

serialworm