Query Caching in PHP For mySQL Performance

Basically you need to cache the query:

 # After: [with memcache]
    $rSlowQuery = mysql_query_cache($sql);
    # $rSlowQuery is an array
    $rows = count($rSlowQuery);
    for ($i=0;$i<$rows;$i++) { }

Reduce Database Calls Check out phpFastCache that support WinCache, MemCache, Files, X-Cache, APC Cache. It's simple for beginners

PHP Caching Class For Database : Your website have 10,000 visitors who are online, and your dynamic page have to send 10,000 same queries to database on every page load. With phpFastCache, your page only send 1 query to DB, and use the cache to serve 9,999 other visitors.

<?php
    // In your config file
    include("php_fast_cache.php");
    // This is Optional Config only. You can skip these lines.
    // phpFastCache support "apc", "memcache", "memcached", "wincache" ,"files", "pdo", "mpdo" and "xcache"
    // You don't need to change your code when you change your caching system. Or simple keep it auto
    phpFastCache::$storage = "auto";
    // End Optionals

    // In your Class, Functions, PHP Pages
    // try to get from Cache first.
    $products = phpFastCache::get("products_page");

    if($products == null) {
        $products = YOUR DB QUERIES || GET_PRODUCTS_FUNCTION;
        // set products in to cache in 600 seconds = 10 minutes
        phpFastCache::set("products_page",$products,600);
    }

    foreach($products as $product) {
        // Output Your Contents HERE
    }
?>

I recently ran into an similar issue, and here's how I resolved it...


Step 1: Add a .user.ini file to your project root (if you don't already have one), and the following directives to the file to enable the mysqlnd_qc plugin and set a TTL for the cache:

; Enables MySQL query caching by PHP
mysqlnd_qc.enable_qc = 1

; Set a default TTL for the caching in seconds
mysqlnd_qc.ttl = 30

Step 2: Add a SQL hint before any query you want cached by mysqlnd_qc.

Here's the hint that must be added to the query:

"/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" .

Here's an example of use:

$res = $mysqli->query("/*" . MYSQLND_QC_ENABLE_SWITCH . "*/" . "SELECT id FROM test WHERE id = 1");

That should do it! You could also cache all queries using the mysqlnd_qc.cache_no_table = 1 directive.

All of this comes from PHP's documentation, here: http://php.net/manual/en/mysqlnd-qc.quickstart.caching.php

I hope that helps!

Tags:

Mysql

Php

Caching