“Smart” Caching System using PDO and Memcache

2019-07-26 09:35发布

I am working on a "smart" caching system that uses pdo and memcache. However, I am stuck at this error. Can you help me out?

My Code:

$session = "a121fd4ztr6";
cache_query("SELECT * FROM `session` WHERE `session` = :session: LIMIT 1;", array(':session:' => $session));

// CACHE QUERY
function cache_query($sql, $params) {
    global $db;
    global $memcache;

    $name = 'querycache-'.md5(serialize(array($sql, $params)));
    $result = $memcache->get($name);

    if (!$result) {
        if(!($db)){
            require("db.php");
        }

        $stmt = $db->prepare($sql);
        $exec = $stmt->execute($params);
        $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $memcache->add($name, $result);
    }

    return $result;
}

db.php sets up a connection to PDO. Memcache connection is already set up. I always get the following error:

Edit: after adding the error mode attribute, I now get a more detailed error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ': LIMIT 1' at line 1' in /chroot/home/html/session.php:170

^What is going on with that?

1条回答
在下西门庆
2楼-- · 2019-07-26 10:26

Looks like $db->prepare() returns an error, so your $stmt variable is not a real PDOStatement object. Use the $db->errorInfo() to see what's going wrong. You can also put it to a try-catch block, if you have set appropriate attributes (see Errors and error handling).

To see if your connection is OK, you also can use try-catch:

try {
    $db = new PDO($dsn, $user, $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}
查看更多
登录 后发表回答