PHP retrieves the number of database queries that generate a page

Source: Internet
Author: User

Many blog software have such a function. For example, it takes xx milliseconds to generate this page and perform xx database queries. So how can this function be implemented? Let me give you a rough idea.

1. Declare global variables in the class Constructor

Defines a global variable $ queries to count the number of database queries generated on the page.

function __construct(){parent::__construct();global $queries;}

2. Modify the encapsulated query () in the Database Class ()

You should use the database class to find the method for encapsulating query (), such as the following:

// Execute the SQL statement public function query ($ query) {// echo $ query. '<br/>'; ++ $ GLOBALS ['querys']; return $ this-> result = mysql_query ($ query, $ this-> link );}

Then, each time a Query is executed, the global variable queries will increase by 1.

3. Write in the method body as follows:

public function content($id = 0){$GLOBALS['queries'] = 0;// something to doecho $GLOBALS['queries'];}

That is simple to implement.

4. Computation of functions executed by PHP scripts

I wrote a blog post about the function used to calculate the execution time of PHP scripts. I will post it here.

// Timing function public function runtime ($ mode = 0) {static $ t; if (! $ Mode) {$ t = microtime (); return ;}$ t1 = microtime (); // list ($ m0, $ s0) = split ("", $ t); list ($ m0, $ s0) = explode ("", $ t); // list ($ m1, $ s1) = split ("", $ t1); list ($ m1, $ s1) = explode ("", $ t1); return sprintf ("%. 3f ms ", ($ s1 + $ m1-$ s0-$ m0) * 1000 );}

Use:

public function content($id = 0){$this -> runtime();$GLOBALS['queries'] = 0;// something to doecho $GLOBALS['queries'];echo $this -> runtime(1);}

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.