0

Ok I have been working my way around Memcache for the last few days, attempting to collate the most helpful articles I can find (Primarily from Stackoverflow)

I understand creating a value using a key in memcache and have read that correct/efficient key naming is important. The best way it seems to make a key unique is to use the $id. My question is how can I make a key unique without having the $id (if for example that $id is just auto incremented within my Mysqli database table)

An example of Memcache inserting and retrieving is the following:

$sql = "INSERT INTO products SET id = $id, name = $name";
// Run Insert Query Here using prepared statement
if (success === TRUE)
{
    //set a key
    $key = 'product_'.$id ;
    $product = array('id' => $id, 'name' => $name);
    $memcache->set($key, $product);
}

This I believe will work fine, but my question is how could I make the key unique if I do not have access to the $id? As I could use the name, but there is a possibility that two users could have the same name.

I hope this makes sense. Any help or guidance would be appreciated.

HireLee
  • 561
  • 1
  • 9
  • 25

2 Answers2

0

You have to create a unique ID,

3 solutions :

  • with uniqid()
  • with this solution UUID generator
  • hash of string (ex : md5('table_name_id:'.$id) or sha1('table_name_id:'.$id) )
Community
  • 1
  • 1
djleop
  • 687
  • 4
  • 18
  • Arh, why did I not think of this. I assume I would have to store the uniqid() within my mysqli database? So everything correlates. – HireLee Feb 07 '13 at 13:40
  • you have to generate a uniqid or uuid for each element of your database, and index the field. Don't drop the autoincrment id, it's always useful. – djleop Feb 07 '13 at 13:45
  • You can eventually generate a key with a hash of your id md5($id) or a hash of a string md5('table_name_id:'.$id) so you can retrieve your key without extra field. – djleop Feb 07 '13 at 13:47
0

If you are using MySQL to automatically generate IDs for you (via an AUTO_INCREMENT column), then why not ask MySQL for the ID it gave to the new row with $mysqli->insert_id()?

Example:

$result = $mysqli->query("insert into products set name='best product ever'");
if ($result === TRUE) {
    // put it into memcached
    $key = 'product_' . $mysqli->insert_id();
    $product = array('id' => $id, 'name' => $name);
    $memcache->set($key, $product);
}
Carsten
  • 17,991
  • 4
  • 48
  • 53
  • The question was : "how could I make the key unique if I do not have access to the $id" – djleop Feb 08 '13 at 08:34
  • I know, but the OP mentioned using MySQL `AUTO_INCREMENT` to generate IDs. It is then imho reasonable to assume that the OP didn't know about the `mysqli::insert_id()` method. While it is not a literal solution to the question, my answer offers an alternative solution to the underlying problem, which is _getting the ID_. If the OP would rather generate IDs himself, he has your answer to refer to. :-) – Carsten Feb 08 '13 at 08:57