Using the same MySQL query with all users without reconnecting to the database

I will try to be simple, so I need to execute a MySQL query (selecting records from a table), let's say that it gives a bad query with cron jobs or something every 5 minutes, and save this query or results to a file or global variable if it is possible and then serve it for all clients (i.e. use the same request for all users without the need to reconnect to this database). Now I know that some of you will tell me to use the cache, but I was looking for it, and if the table changes, a new cache appears and my table keeps changing, now I don’t care if the table has changed, I just want to serve one and the same same request for all customers. Is it possible? your recommendations please. Thanks.

The cache expires automatically when the table is modified (insert, update, delete, etc.). And my table is constantly changing, so can I keep the cache even if the table has been modified? or should I look for another solution?

+6
source share
2 answers

If the result set is not too large, you can cache it in the generated script like this:

file_put_contents( 'mycache.php', '<?php return ' . var_export($results, true) . ' ?>' ); 

Then, to use it:

 $results = include 'mycache.php'; 
+1
source

If you always use the same method (function, class) to read and write the database,
you can always put a cache expiration after each action

eg:

 function add() // update, delete { if (added) $this->expire_cache(); } function search() { if (results) $this->set_cache(results); } function expire_cache() { // do expire or purge cache } function set_cache( $db_results ) { // saving the database result OR computed result into cache // memcache, redis, disk cache or anything } 

However, the purpose of caching is to serve the request without the need for an expensive resource, such as a database request,
but if you need to update very often, the cache implementation is not so useful

Memcache example: http://php.net/manual/en/book.memcache.php

you will need to compile the memcache module, configure and start the memcache server to use memcache

0
source

All Articles