Search code examples
phpcachingredisquery-cache

how to get array value from redis cache key


Below is my php script,I am selecting data from database and then storing resultset array into redis cache using set command but not able get exactly data when I am trying to get using get command

<?php
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);

    mysql_connect("localhost", "test", "testing123") or die(mysql_error());
    mysql_select_db("test") or die(mysql_error());

    $query = "select id from example where name = 'new_data'";
    $querykey = "KEY" . md5($query);

    echo $querykey;
    $result = $redis->get($querykey);
    echo "<pre>";
    print_r($result);

    if (!$result) {
        $result = mysql_fetch_array(mysql_query("select id from example where name = 'new_data'")) or die('mysql error');
        print_r($result);
        $redis->set($querykey, $result);
        print "got result from mysql\n";
        return 0;
    }

    print "got result from redis\n";
    return 0;
?>

When I do print_r($result) it gives only Array.What is the problem in approach or is there any other method to do this.

Any help appreciated. Thank you


Solution

  • If you want to store a result set corresponding to a key in Redis either json_encode the string or store the array result as a SET in Redis.