简体   繁体   中英

How can I count the total number of MySQL queries used per page?

Is there a built-in function in PHP or MySQL that will provide the total number of MySQL queries used on a page? I've seen on a lot of sites (mainly forums) they have a message at the bottom saying something like "Page generated in 0.6 seconds with 20 queries".

If there's nothing built in then I'll add something to my database class to count them, but it seems like the kind of functionality that would already be available.

Option one would be to pass all of your queries through a wrapper:

function custom_mysql_query($sql)
{
    $GLOBAL['query_count'] ++;
    return mysql_query($sql);
}

Please note that's for illustration only and without error handling, etc.

You could query MySQL for the number of queries run:

mysql> SHOW STATUS LIKE 'Com_select';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| Com_select    | 2     | 
+---------------+-------+
1 row in set (0.00 sec)

You might want to do something like:

SHOW STATUS LIKE 'Com_%';

and then add together Com_select, Com_update, Com_insert and Com_delete

我所做的是创建一个重要的SQL查询类,每次运行类中的查询方法时,它会向一个名为querycount的变量添加1,这样我就有了一个运行总计。

There is nothing built into PHP's native mysql/mysqli extensions. If you're using a DB abstraction layer, there may be some type of analysis/benchmarking built in that will give you that info.

Off-hand, I know Kohana does this with the Profiler library. I would assume that most frameworks' DB libraries do something similar.

If you are hesitant to use a 3rd party framework or database abstraction layer, I have had success by simply subclassing PHP5's built-in PDO class. You can add some basic benchmarking information and query counts, and pass the query() or execute() calls through to the parent class.

In order to avoid globals, in your db class:

class db {
    public static $query_count = 0;

    public static function query($str) { 
        self::$query_count++;
        // your db query method here
    }
}

Then just access your static query count like this:

<?= db::$query_count ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM