简体   繁体   English

如何计算每页使用的MySQL查询总数?

[英]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? PHP或MySQL中是否有内置函数可以提供页面上使用的MySQL查询总数? 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". 我在许多网站(主要是论坛)上看到过,他们在底部有一条消息,上面写着“在0.6秒内生成20页查询页面”。

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中查询运行的查询数:

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 然后将Com_select,Com_update,Com_insert和Com_delete加在一起

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

There is nothing built into PHP's native mysql/mysqli extensions. PHP的本机mysql / mysqli扩展中没有内置任何东西。 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. 副手,我知道Kohana使用Profiler库做到这一点。 I would assume that most frameworks' DB libraries do something similar. 我认为大多数框架的DB库都做类似的事情。

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. 如果您对使用第三方框架或数据库抽象层犹豫不决,我通过简单地继承PHP5的内置PDO类获得了成功。 You can add some basic benchmarking information and query counts, and pass the query() or execute() calls through to the parent class. 您可以添加一些基本的基准测试信息和查询计数,并将query()execute()调用传递给父类。

In order to avoid globals, in your db class: 为了避免全局变量,在db类中:

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 ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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