Php file cache array implementation in a pilot project, I need to randomly read a record from the sqlite3 database to the user, the data table to read now has 23850 records, by skemu classification, generally, each skemu has more than 3000 records. I used sqlite3's random query statement: & nbsp; $ query & quot; SELECT * FROMshitiWHEREskem PHP file cache array implementation.
In a pilot project, I need to randomly read a record from the sqlite3 database to the user. the data table to be read now has 23850 records, which are classified by skemu, generally, each skemu has more than 3000 records. I used the sqlite3 random query statement:
$query="SELECT * FROM shiti WHERE skemu = " . intval($kemuid) . " order by random() limit 1";
I didn't feel a significant delay on my current computer, but when I switched the server to a machine with P4 1.8G m memory, I felt that the data reading speed was very slow, it takes two or three seconds to read data. If a user needs to obtain a random record and execute such a random query, the bottleneck will occur in the database query process, it is hard to imagine how this performance can adapt to simultaneous access by many users. To this end, I want to reduce the number of database queries. first, I need to retrieve the record id and put it in the array. then, I will randomly retrieve a record from it and save it as a file for later reading, this reduces the number of database queries.
The following functions read the id set:
Static function getIDs ($ kemuid) {$ cachefile = "cache/". $ kemuid. ". cache"; $ datas = array (); if (! File_exists ($ cachefile) | time () <(filemtime ($ cachefile) + 14400) // The cache does not exist or exceeds 4 hours {global $ data; // Read id set $ query = "SELECT sid FROM shiti WHERE skemu = ". intval ($ kemuid); $ res = $ data-> query ($ query); while ($ r = $ data-> fetchArray ($ res )) {$ datas [] = $ r ['Sid '];} // write the cached file_put_contents ($ cachefile, serialize ($ datas ));} else {// read cache $ fp = fopen ($ cachefile, 'r'); // read $ datas = unserialize (fread ($ fp, filesize ($ cachefile ))); // deserialization and assignment} return $ datas ;}
Call its random record reading function:
static function getRondam($kemuid) { global $data; $ids=self::getIDs($kemuid); $index=rand(0,count($ids)-1); $id=$ids[$index]; $query="SELECT * FROM shiti WHERE sid = " . intval($id); $res = $data->query($query); $r = $data->fetchArray($res); $r['da']=$s; return $r; }
This is much faster than executing a random query, but it is still a little slower than generating an HTML cache. However, you need to expose more data to the client or store more caches, I think this is already a balanced solution.
The main points of this solution are array serialization and deserialization, which should be easily understood.