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(开发者_如何学JAVA);
}
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, i.e. with PEAR's Cache or Cache_Lite
- memcached
- shared memory as cache, i.e. 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.
精彩评论