Home  >  Article  >  Backend Development  >  Using static variables as Cache_PHP tutorial

Using static variables as Cache_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:05:47874browse

I guess you have all encountered the following situation
I have two tables, magazine (magazine information) and subscibe (subscription information). In the subscibe table, I have a magazine_id to match the number in the magazine table. Association
Now I want to make a list of browsing subscription information. There is a column in this list that displays the name of the magazine (the name field of the magazine table). One way is to use join to make an association between the two tables. Replace magazine_id with name, but this list is a search result, and the SQL query statement is spliced ​​together. If join is added, the logic of splicing SQL will become a bit complicated, so it is better to simply make a select * from subscibe where ...., and then it will be simpler to query the magazine_id in the result set. This brings up another problem. I don’t want too many repeated queries in my program. For example, there are 10 pieces of data in the result set. All about the same magazine_id, I would have 9 more duplicate queries, so I decided to do this

function MagazineInfoById($magazine_id){
global $db;
static $magazine_info;

if (!isset($magazine_info[$magazine_id])){
$magazine_info[$magazine_id] = $db->getRow('select * from magazine where id = '. $magazine_id) ;
}

return $magazine_info[$magazine_id];
}

while (....){
$magazine_info = MagazineInfoById($magazine_id);
.....
}


The static variable $magazine_info in MagazineInfoById() becomes a cached thing, which in some cases can greatly reduce the query time times to avoid repeated queries


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445105.htmlTechArticleI guess you must have encountered the following situation. I have two tables, magazine (magazine information) and subscibe (Subscription information), I have a magazine_id in the subscibe table and the magazine table...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn