1

I'm a bit confused on memcached and PHP when used with SQL queries.

Practically every guide I've come across does something resembling this:

$querykey = "KEY" . md5($query);
$result = $mem->get($querykey);

What I don't understand, is why they all seem to store a hashed version of the actual query as the key?

Wouldn't it be better to give it a proper name, that way it's easier to reference anywhere in your script and invalidate it if needed?

Like this guide and this guide.

Barmar
  • 741,623
  • 53
  • 500
  • 612
NaughtySquid
  • 1,947
  • 3
  • 29
  • 44

2 Answers2

3

Yes, you can use anything you want as the key in memcached, within the key constraint supported by memcached (a string 250 bytes or less).

The key doesn't necessarily have anything to do with one specific SQL query. It might not be something that came from a database at all.

Some apps store whole fragments of HTML in memcached, like a <div> that is ready to use as a drop-down list in a web page for example. The content of which might include the result of several SQL queries, integrated into the HTML fragment.

The suggestion to use a hash of a specific SQL query is probably just an example shown in tutorials. Like naming your class "Foo" or "MyClass" — you wouldn't actually use those names in a real application.

P.S.: The two tutorials you link to are so similar, I suspect the one from November 2015 is borrowing some of its content from the earlier one from May 2014.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
  • That's great thank you. As I'm making my CMS use memcached as we've had traffic spikes suck away too much ram from all the sql queries. So I'm putting some into memcached, but I'm naming them as some (like config options: site name/template name etc) are updated hardly ever - so i want to have no expiry on them and expire them by name manually if i update them in the database :) – NaughtySquid Mar 07 '18 at 22:02
2

I think that is a good question. First Point generate an md5 hash is the easiest way to get a unique key of a string. So you don't need to generate a complicate key.

But in general you can use every key you want and build your own structure.

https://secure.php.net/manual/de/memcached.getallkeys.php

Here is a good example how to get all keys and delete them.

René Höhle
  • 26,716
  • 22
  • 73
  • 82