简体   繁体   中英

cache mysql query result?

I use a several mysql queries on a page to fetch data from multiple tables using mysqli prepare statements.

Lets say i have like 20 queries from database tables on a page. Since there are so many queries, I would like to improve the performance by storing the results in cache for some minutes? Is it good idea? If yes, how I can store the results using cache for the , for example, following query?

$city = "Amersfoort";

if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $stmt->bind_result($district);
    $stmt->fetch();
    printf("%s is in district %s\n", $city, $district);
    $stmt->close();
}

Thanks.

If the SQL statements are cheap in processing, you probably don't need to cache them. If they require hefty calculations or run on really large datasets, you might need a cache. Remember that the cache needs to be faster than the SQL query.

There are several ways to cache in PHP:

  • File cache, serialzing the data and storing it into a file named like the hash of the query. Remember that getting cache lifetime, concurrent accesses and so is hard -so consider using a library that does it, ie with PEAR's Cache or Cache_Lite
  • memcached
  • shared memory as cache, ie by using APC functions like apc_add

You also might want to cache the complete page or parts of the page instead of single queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM