【问题标题】:Need a way to add a function to query function of mysqli class需要一种方法来添加一个函数来查询 mysqli 类的函数
【发布时间】:2014-02-19 02:21:31
【问题描述】:

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

$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 = new MyDB($host, $user, $pass, $dbname, $port); 然后调用 $db->query(...my query...);

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

【问题讨论】:

  • 为什么需要global关键字?将这些 $nb_queries,$timer_queries 设为 mysqli 类的受保护修饰符。
  • 基本上我应该以这种方式调用查询执行 $req_return = parent::query($query);
  • Shankar,我使用这些是为了在其他地方回显变量。因此我将它们设置为 0,然后在页脚中回显它们。请参阅下面的工作示例。

标签: php class mysqli overriding extends


【解决方案1】:

你的脚本有错误吗?

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

这条线正确吗?

$req_return = mysql_query($query);

或者应该是:

$req_return = mysqli_query($query);

【讨论】:

  • mysqli_query($query) 需要两个参数...反正我已经解决了。谢谢!
【解决方案2】:

搞定了...在现有系统中更改所有 $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';?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2018-12-07
    • 2011-09-13
    相关资源
    最近更新 更多