PHP Cache Cash

Source: Internet
Author: User
Tags php mysql extension commerce store
(Conversion) PHP Cache Implementation SQL query cache is suitable for PHP programmers who are interested in cache SQL queries to reduce the load of database connection and execution and improve script performance. This topic describes how many sites use databases as the container for storing site data. The database contains the producer information, directory structure, article, or message book. some data may be completely static, which will be of great benefit from a cache system. Such a system is implemented by caching S (to) PHP

SQL query cache is suitable for PHP programmers who are interested in caching SQL queries to reduce database connection and execution load and improve script performance. This topic describes how many sites use databases as the container for storing site data. The database contains the producer information, directory structure, article, or message book. some data may be completely static, which will be of great benefit from a cache system. Such a system caches the SQL query results to a file of the system for storage, thus blocking connection to the database, constructing the query and obtaining the returned results, and improving the response time. Some system databases are not stored on WEB servers. Therefore, a remote connection (TCP or similar) is required, or a large amount of data is obtained from the database, in this way, you have to endure more time, which is determined by the system response time and resource utilization. This tutorial uses MySQL as the database. You need to install MySQL (www.mysql.com is valid for download) and activate php mysql extension (activated by default ). To query databases, you need to have basic knowledge about SQL (Structured Query Language. Why do I cache the SQL query results? The cache query results greatly improve the script execution time and resource requirements. Caching SQL query results also allows you to process data later. If you use the file cache to store the output results of all scripts (HTML output), this may not work. When you execute an SQL query, the typical processing process is: l connect to the database l prepare the SQL query l send the query to the database l obtain the returned results l close the database connection the above method is very resource-consuming and the opposite affects the script performance. Coordination can only be achieved by obtaining a large amount of returned data and the location of the database server. Although continuous connection can improve the load when connecting to the database, it consumes a lot of memory resources. if a large amount of data is obtained, the storage duration will be very short. Create an SQL query: SQL (Structured Query Language) query is used as an interface to operate the database and its content. SQL can be used to define and edit the table structure, insert data to the table, and update or delete information in the table. SQL is a language used for data communication. In most PHP databases, extensions (MySQL, ODBC, Oracle, and so on) pass SQL queries to the database to manage the entire process. In this tutorial, only the select language is used to obtain 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 program's needs, the cache can take multiple forms. The most common three methods are: l time-triggered cache (expiration timestamp) l content change-triggered cache (when data changes are found, the cache is updated accordingly) l manually trigger the cache (manually inform the system of information expiration and force a new cache) your cache needs may be one or more of the above principles. This tutorial will discuss how to trigger the time. However, in a comprehensive Cache mechanism, the combination of the three methods will be used. Cache results: the basic cache uses two PHP functions: serialize () and unserialize () (Note: These two functions represent serialization and deserialization respectively ). The serialize () function is used to store PHP values. it ensures that the types and structures of these values are not lost. In fact, PHP's session extension uses serialized variables to store session variables ($ _ SESSION) in a system file. The unserialize () function is opposite to the preceding operation and returns the serialized string to its original structure and data content. In this example, an e-commerce store is used as an example. The store has two basic tables, categories and products (the original database table name here). The product table may change every day and the categories remains unchanged. To display the product, you can use an output cache script to store the output HTML results to a file. However, the categories table may need to be processed later. For example, all directories are displayed through the variable category_id (obtained through $ _ REQUEST ['Category _ id']). you may want to highlight the selected directory. In this example, the time-triggered cache technology is used to set the expiration time for the cached SQL output after a period of time. In this special example, the time is set to 24 hours. Serialization example: l connect to the database l execute the query l get all the results to form an array so that you can access the l serialization array l save the serialized array to the file $ file = 'SQL _cache.txt '; $ link = mysql_connect ('localhost', 'username', 'password') or die (mysql_error (); mysql_select_db ('shop ') or die (mysql_error ()); /* construct an SQL query */$ query = "SELECT * FROM categories"; $ result = mysql_query ($ query) or die (mysql_error ()); while ($ record = mysql_fetch_array ($ result) {$ records [] = $ record;} $ OUTPUT = seria Lize ($ records); $ fp = fopen ($ file, "w"); // open the file fputs ($ fp, {output}%fclose(%fp%%%%%% SQL _cache.txt) with write permissions, the content may be like this: 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 the array of the numeric index and an associated array (that is why the data seems to have happened twice), one is the numeric index and the other is the string index. Cache: to use the cache, you need to use the unserialize () function to restore the data to the original format and type. You can use the file_get_contents() to read the content of the SQL _cache.txt file and assign it to a variable. Note: This function is valid in PHP4.3.0 and later versions. If you are using an old version of PHP, a simple method is to use the file () function (read the entire file to an array, and each row becomes an array ). The implode () function is used to connect each element of the array into a string and then use unserialize () for deserialization. // File_get_contents () is suitable for PHP <4.3.0 $ file = 'SQL _cache.txt'; $ records = unserialize (implode ('', file ($ file ))); now you can use the $ records array to obtain the original query data: foreach ($ records as $ id => $ row) {print $ row ['Category _ name']."
";} Note that $ records is an array (a numeric index column containing the query results-each row is a number and a string... it is really messy. Put them in one piece: decide whether to cache based on the time in this example. If the modified timestamp of a file is greater than the current timestamp minus the expiration timestamp, the file will be cached; otherwise, the cache will be updated. L check whether the file exists and the timestamp is earlier than the set expiration time l obtain the records stored in the cache file or update the cache file $ file = 'SQL _cache.txt'; $ expire = 86400; // 24 hours (unit: Seconds) if (file_exists ($ file) & filemtime ($ file)> (time ()-$ expire )) {// Get the cached record $ records = unserialize (file_get_contents ($ file);} else {// create a cache using the serialize () function} to append other possible records: l store the cache results in the shared memory to get a faster speed l add a function to run SQL queries randomly and check whether the output is consistent with the cache output. If they are inconsistent, update the cache (the probability of this function running count can be set to 1/100 ). The hash algorithm (such as MD5 () can be used to determine whether the string or file has changed. L adds an administrator function to manually delete the cache file to force update the cache (for example, when the file_exists () function returns false ). You can use the unlink () function to delete files. Script: $ file = 'SQL _cache.txt'; $ expire = 86400; // 24-hour if (file_exists ($ file) & filemtime ($ file)> (time () -$ expire) {$ records = unserialize (file_get_contents ($ file);} else {$ link = mysql_connect ('localhost', 'username', 'password ') or die (mysql_error (); mysql_select_db ('shop ') or die (mysql_error ();/* construct an 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 );} // end else // The query result is in the array $ records foreach ($ records as $ id => $ row) {if ($ row ['Category _ id'] = $ _ REQUEST ['Category _ id']) {// print the selected directory in bold''. $ Row ['Category _ name'].'
';} Else {// other directories are displayed in the regular font print $ row ['Category _ name'].'
';}} // End foreach About the Author Ori Staub is an intermediate system analyst, developer, and consultant focused on WEB-based solutions. You can contact him by email OS @zucker-staub.com. Original article address: http://www.zend.com/zend/tut/tutorial-staub2.php translation is not very good, please forgive me! This article is translated by arcow. Email: phpers + csdn@gmail.com
?

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.