I have a function like this:
function query($query)
{
/* If query result is in cache already, pull it */
if $cache->has(md5($query))
return $cache->get(md5($query));
/* Do the actual query here. mysqli_query() etc, whatever u imagine. */
/* Set the cache with 10 minute expiration */
$cache->set(md5($query), $queryOutput, array(10));
}
So basically, if I query SELECT * FROM USERS
, it is cached automatically for 10 minutes.
I don't know if md5 is safe to rely on. For once, it creates 32 character string, which sounds a bit overkill. Second, md5 is known to give same character string as output on certain inputs. Is there any alternatives to md5 to identify an unique cache key? There is very little chance, that two completely different SQL queries may get the same md5 output and break some pages of the website, but it is still a chance I should predict right now and code accordingly.
One more thing is, I feel like such use of functions is considered bad practise. A new user may be inserted to USERS table
after my cache, but SELECT * FROM USERS
will still get the same md5 output, hence, ignore the newly inserted user. They may register with same nickname few times in 10 minute duration.
Should I pass a second parameter to my sensitive queries, like query($query, 'IGNORECACHE')
? It doesn't sound logical to me. There will be too much things to keep in mind. How do you guys handle such issues?
I will appreciate it if you can reply my first question about md5 alternative for this case, and a short explanation of good use of SQL caching on my second question would be greatly appreciated.
Thank you.