需要一种方法来添加函数来查询 mysqli 类的函数



我正在尝试使用标准 mysqli 类在充满$db>查询调用的现有站点上实现 MySQL 查询执行时间测量

$db = new mysqli($host, $user, $pass, $dbname, $port);

我想做的是扩展查询以在每次调用时执行更多操作,例如添加一些操作。如果我只是扩展类,这会起作用吗?

class MyDB extends mysqli {
//The function to count the number of queries and their execution time
function query($query)
{
        //We increase the queries counter by 1
        global $nb_queries,$timer_queries;
        $nb_queries++;
        //Execute the query and time the execution time
        $beginning = timer();
        //Execute the query and save the result in a variable
        $req_return = mysql_query($query);
        //We add the query duration to the total
        $timer_queries += round(timer()-$beginning,6);
        return $req_return;
}
}

像这样连接 $db = 新的 MyDB($host、$user、$pass、$dbname、$port); 然后调用$db->查询(...我的查询...

但这对我不起作用...有关如何实现这一目标的任何提示将不胜感激。

你的脚本给出任何错误吗?

看起来您可能使用了错误的功能。

这句话对吗?

$req_return = mysql_query($query);

或者应该是:

$req_return = mysqli_query($query);

让它工作...在现有系统中更改所有$db>查询调用太困难了,因此这是我所做的工作示例:

$host = "localhost";
$user = "user"; 
$pass = "pass"; 
$dbname = "test";
$port = "3306";
//------- new DB class to extend the functionality
$nb_queries = 0;
$timer_queries = 0;
function timer() {
    $time = explode(' ', microtime());
    return $time[0]+$time[1];
}
class MyDB extends mysqli {
  //The function to count the number of queries and their execution time
    function query($query)
    {
            //We increase the queries counter by 1
            global $nb_queries,$timer_queries;
            $nb_queries++;
            //Execute the query and time the execution time
            $beginning = timer();
            //Execute the query and save the result in a variable
            $req_return = parent::query($query);
            //We add the query duration to the total
            $timer_queries += round(timer()-$beginning,6);
            return $req_return;
    }
}
@ $db = new MyDB($host, $user, $pass, $dbname, $port);
if (mysqli_connect_errno()) {
    echo 'Error: Could not connect to database. Please let the IT know and try again later.';
    exit;
}

用法:

$var = $db->query("select * table");

并在您的页面 HTML 中使用它

<?php echo $nb_queries.' queries in '.$timer_queries.' seconds';?>

最新更新