Z
Z
zaart2021-09-12 00:30:34
PHP
zaart, 2021-09-12 00:30:34

How to identify unique Memcached keys?

Hello!

I'm learning Memcached and, it seems, everything is working out so far. But the question arose, how to identify unique keys?

Well, for example, I have a database query that returns the number of attempts by a specific user:

The code

if (class_exists('Memcached')) {
    $ttl = 3600;
    $cache = new Memcached();
    $cache->addServer("127.0.0.1", 11211);
    if(($cache->get('num_att')) != null) {

        $total_count = $cache->get('num_att');

    } else {
        $sql = "SELECT * FROM sub_all WHERE user_id IN (?)";
        if ($query = $db->prepare($sql)) {
            $query->bind_param("i", $id);
            $query->execute();
            $result = $query->get_result();
            $exist = $result->num_rows;
            $total_count = $result->fetch_array();
            $cache->set('num_att', $total_count, $ttl);
        } else {
            $errBox = 'Ошибка. Пожалуйста, повторите попытку.';
            $stop_error = true;
        }

    }
}else {
    die("Ошибка при подключении к кеш-серверу");
}



And now the cache works, but it will return one result to all users, and I need everyone to have their own.

I had an idea to hash the keys, but how to check them later, how to store them?

Please share your solutions to this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Syomov, 2021-09-12
@zaart

You have an id, you can include it in the name of the key. for example "num_att_$id". And in the same way, when saving the number of attempts to use the same key. There is no need to store anything else.
Keys can be deleted by prefix if you need to clear this cache. There is no direct functionality for this in memcached, but there are workarounds.
By the way, you don't need to check the cache and throw an error. The code should work without it. Moreover, the error message is clearly incorrect - the presence of the module is checked, and not the connection. =) You just need to correctly wrap the cache access with a check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question