Go The Redemption of PHP cache

Source: Internet
Author: User
Tags php database php mysql php mysql extension commerce store
Go Implementation of PHP cache

SQL query cache is suitable for readers this tutorial is suitable for PHP programmers who are interested in caching SQL queries to reduce the load on database connections and execution, and improve script performance. Outlines many sites use databases as containers for site data storage. The database contains production information, directory structure, articles, or message books, some of which are likely to be completely static, and will benefit greatly from a cache system. Such a system can block the connection of the database by caching the results of the SQL query to a file in the system, thereby increasing the response time by constructing the query and obtaining the return result. Some system databases are not placed on the Web server, which requires a remote connection (TCP or something like that), or a large amount of data from the database, so you have to endure more time, which depends on the system response time and resource utilization. The premise of this tutorial is to use MySQL as a database. You need to install MySQL (www.mysql.com download is valid) and activate the PHP MySQL extension (which is activated by default). Because you want to query the database, you need to know some basic knowledge of SQL (Structured Query language). Cache SQL Query Results why would you cache query results? Caching query results can greatly improve script execution time and resource requirements. Caching SQL query results also allows you to post-process data. If you use the file cache to store the output of all scripts (HTML output), this may not work. When you execute an SQL query, the process of the code is: L Connect database L Prepare SQL query L send query to database L Get return result L Close database connection The above method is very resource-intensive and adversely affects the scripting sex Yes. These two elements can only be reconciled by the large number of returned data and the location of the database server. Although persistent connections can improve the load when connecting to a database, it is very memory intensive, and if you get a large amount of data, the whole time of storage is very short. Create an SQL query: SQL (Structured Query Language) query is used as an interface to manipulate the database and its contents. SQL can be used to define and edit the structure of a table, insert data into a table, update or delete information in a table. SQL is the language used to communicate with data, and in most PHP database extensions (mysql,odbc,oracle, etc.) manage the entire process by passing SQL queries into the database. In this tutorial, only the Select language is used to get the data in the database. The data will be cached and then used as the data source. Decide when to update the cache: Depending on the needs of the program, the cache can take many forms. The most common 3 ways are: L time trigger cache (expired timestamp) L content changes trigger cache (after discovery data changes, update cache accordingly)L Manually trigger the cache (manually informing the system that the information is overdue and forcing a new cache) your cache requirements may be one or more of the above principles of synthesis. This tutorial discusses how time is triggered. However, in a comprehensive caching mechanism, 3 methods of synthesis will be used. Cached results: The basic cache is PHP two functions serialize () and Unserialize () (these two functions represent serialization and deserialization respectively). The function serialize () is used to store the value of PHP, which guarantees the type and structure of the values without losing them. In fact, the session extension of PHP is a serialized variable that stores the session variable ($_session) in a file in the system. The function unserialize () Reverses the above operation and returns the serialized string to its original structure and data content. In this example, take an e-commerce store as an example. The store has 2 basic tables, categories and products (here is the original database table name). The Product table may change every day, and categories remains constant. To display the product, you can use an output cache script to store the output HTML results into a file. However, the Categories table may require post-processing. For example, all directories are displayed through the variable category_id (obtained through $_request[' category_id '), and you may want to highlight the currently selected directory. Table Categories Structure FieldType Keyextracategory_idcategory_namecategory_descriptionint (Ten) Unsignedvarchar (255) Textpriauto_incremen in this example, the time-triggered cache technology is used to set a period of time after which the cached SQL output expires. In this particular case, the set time is 24 hours. Serialization Example: L connect to database L Execute query l get all results form an array so that you can access L serialized array L save serialized array to file $file = ' Sql_cache.txt ' ; $link = mysql_connect (' localhost ', ' username ', ' password ') or Die (Mysql_error ()); mysql_select_db (' Shop ') or Die (Mys Ql_error ());/* Construct SQL query */$query = "SELECT * FROM Categories", $result = mysql_query ($query) or Die (Mysql_error ()), while ($record = Mysql_fetch_arr Ay ($result)) {$records [] = $record;} $OUTPUT = serialize ($records); $fp = fopen ($file, "w"); Open the file as Write permission fputs ($fp, $OUTPUT); fclose ($fp); View Sql_cache.txt file, the contents of which may resemble the following: a:1:{i:0;a:6:{i:0;s:1: "1"; s:11: " category_id "; s:1:" 1 "; I:1;s:9:" Computers "; s:13:" Category_name "; S:9:" Computers "; i:2;s:25:" Description for Computers "; s:20:" Category_description "; s:25:" description for Computers ";}} This output is the internal representation of its variables and types. If you use the Mysql_fetch_array () function to return an array of numeric indexes and an associative array (that's why the data looks like it happened two times), one is a numeric index and the other is a string index. Using caching: To use the cache, you need to use the function unserialize () to restore the data to the original format and type. You can use the file_get_contents () function to read the contents of the Sql_cache.txt file and assign it to a variable. Please note: This function is valid in PHP4.3.0 and above. If you are using an older version of PHP, an easy way is to use the file () function (read the entire document into an array, each line becomes an array). The implode () function is used to concatenate elements of an array into a string and then deserialize using Unserialize (). File_get_contents () is suitable for PHP < 4.3.0$file = ' sql_cache.txt '; $records = unserialize (Implode (', File ($file))); You can now pass the $records array and get the data from the original query: foreach ($recordsas $id = = $row) {print $row [' category_name ']. " 
";} Note that $records is an array (a numeric index column that contains the results of the query--each row is a number and a string ...). A row of chaos). Put them in one piece: Based on the time in this example, decide whether to cache. If the timestamp of the file modification is greater than the current time stamp minus the expiration timestamp, then cache is used, otherwise the cache is updated. L Check if the file exists and the timestamp is less than the expiration of the setting L get the records stored in the cache file or update the cache file $file = ' sql_cache.txt '; $expire = 86400; 24 Hours (units: seconds) if (file_exists ($file) && filemtime ($file) > (Time ()-$expire)) {//Get records in cache $records = u Nserialize (file_get_contents ($file));} else {///create cache through serialize () function append other possible: L store cached results in shared memory for faster speed L add a function to run the SQL query randomly and check if the output is consistent with the cached output. If not, update the cache (the probability of this function's run count can be set to 1/100). A hashing algorithm (such as MD5 ()) helps to determine whether a string or file has changed. L Add an administrator function to manually delete this cache file to force the update of the cache (such as when the File_exists () function returns false). You can use the function unlink () to delete a file. Script: $file = ' sql_cache.txt '; $expire = 86400; 24 Hours if (file_exists ($file) && filemtime ($file) > (Time ()-$expire)) {$records = Unserialize (file_ge T_contents ($file));} else {$link = mysql_connect (' localhost ', ' username ', ' password ') or Die (Mysql_error ()); mysql_select_db (' Shop ') or Die (Mysql_error ()); /* ConstructCreate SQL query */$query = "SELECT * FROM Categories"; $result = mysql_query ($query) or Die (Mysql_error ()); while ($record = Mysql_fetch_array ($result)) {$records [] = $record; } $OUTPUT = serialize ($records); $fp = fopen ($file, "w"); Fputs ($fp, $OUTPUT); Fclose ($FP);} The end else//query result is in the array $records foreach ($records as $id + = $row) {if ($row [' category_id '] = = $_request[' category_id ']) {//Selected directory displays bold print ''. $row [' category_name ']. '
'; } else {//other directories display print $row in regular font [' Category_name ']. '
'; }}//end foreach about author Ori Staub is a mid-level system analyst focused on Web-based solutions, [email protected]?? him. The original address: http://www.zend.com/zend/tut/tutorial-staub2.php translation is not too good, please forgive me! This article is translated by Arcow. Email:[email protected]
?
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.