How PHP improves access efficiency-Cache

Source: Internet
Author: User
Tags php mysql php mysql extension commerce store

In terms of speed, static pages are much faster than dynamic pages, such as PHP. This is without a doubt, but the flexibility of static pages is poor.
Key to static pages:
In fact, static pages are page-level caches, which are equivalent to caching the entire HTML page and skipping the database to directly read files.

Ob_start () function: Open the output buffer.
Function Format void ob_start (void)
Note: When the buffer zone is activated, all non-file header information from the PHP program is not sent, but stored in the internal buffer zone. To output the buffer content, you can use ob_end_flush () or flush () to output the buffer content.

Flush: refresh the buffer content and output it.
Function Format: flush ()
Note: This function is frequently used and highly efficient.

Ob_get_contents: returns the content of the internal buffer.
Function Format: String ob_get_contents (void)
Note: This function returns the content in the Current Buffer. If the output buffer is not activated, false is returned.

Ob_get_length: returns the length of the internal buffer.
Function Format: int ob_get_length (void)
Note: This function returns the length of the Current Buffer. It is the same as ob_get_contents. If the output buffer is not activated, false is returned.

Ob_end_clean: Delete the content of the internal buffer and disable the internal buffer.
Function Format: void ob_end_clean (void)
Note: This function will not output the content of the internal buffer but delete it.

Ob_end_flush: sends the content of the internal buffer to the browser and closes the output buffer.
Function Format: void ob_end_flush (void)
Description: This function sends the content of the output buffer (if any)

Ob_implicit_flush: Enables or disables absolute refresh.
Function Format: void ob_implicit_flush ([int flag])
Note: the buffer zone is disabled by default. After absolute output is enabled, the output of each script is directly sent to the browser, and you do not need to call flush ()
The specific applications include ob_start () and ob_get_contents.
About cache: including page-level cache, database-level cache, and page-level cache generally access keys. Database-level cache is currently popular for writing memory. Here we will introduce writing files .. (Reprinted)

SQL query Cache

Suitable for readers

This tutorial is applicable to PHP programmers who are interested in caching SQL queries to reduce the load on database connection and execution and improve script performance.

Overview

Many sites use databases as containers 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.

Prerequisites

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.

Cache SQL query results

Why cache 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:

Connect to database

Prepare SQL query

Send query to database

Get returned results

Close database connection

The above method occupies resources and, on the contrary, 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) queries are used as interfaces to operate databases and their 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:

Time-triggered cache (expired timestamp)

Content Change triggers cache (when data changes are detected, the cache is updated accordingly)

Manually trigger the cache (manually inform the System of Information expiration and force a new cache)

Your cache requirements 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:

Basically, the 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.

Table categories Structure

Field

Type

Key

Extra

Category_id

Category_name

Category_description

INT (10) unsigned

Varchar (255)

Text

PRI

Auto_incremen

 

 
In this example, the time-triggered cache technology is used to set the cache SQL output to expire after a period of time. In this special example, the time is set to 24 hours.

Serialization example:

Connect to database

Execute Query

Obtain all the results to form an array so that you can access

Serialized Array

Saves serialized arrays to files

$ 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 = serialize ($ records );

$ Fp = fopen ($ file, "W"); // open the file with write permission

Fputs ($ FP, $ output );

Fclose ($ FP );

The SQL _cache.txt file may contain the following content:

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.

Use 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']. "<br> ";

}

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:

The cache is determined 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.

Check whether the file exists and the timestamp is earlier than the set expiration time

Obtain records stored in cached files or update cached files

$ File = 'SQL _cache.txt ';

$ Expire = 86400; // 24 hours (unit: seconds)

If (file_exists ($ file )&&

Filemtime ($ file)> (Time ()-$ expire ))

{

// Obtain cache records

$ Records = unserialize (file_get_contents ($ file ));

} Else {

// Use the serialize () function to create a cache

}

Additional possibilities:

Store the cache results in the shared memory for faster speed.

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.

Add an administrator 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 hours

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']) {

// The selected directory displays the bold characters

Print '<B>'. $ row ['category _ name']. '</B> <br> ';

} Else {

// Use the regular font to display other directories

Print $ row ['category _ name']. '<br> ';

}

} // End foreach

About the author

Ori Staub is an intermediate system analyst, developer, and consultant who focuses on web-based solutions. You can contact him by email OS @zucker-staub.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.