0

I am trying to implement a MySQL query execution time measurement on the existing site that is full of $db->query calls using the standart mysqli class

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

what I would like to do is to extend the query to do more each time it's called like to add a few actions. Would this work if I just extend the class?

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;
}
}

connect like so $db = new MyDB($host, $user, $pass, $dbname, $port); and then call $db->query(...my query...);

but this is not working for me... any hints on how to achieve this would be greatly appreciated.

2 Answers2

0

Does your script give any errors?

Looks like you might be using the wrong function.

Is this line correct?

$req_return = mysql_query($query);

or should it rather be:

$req_return = mysqli_query($query);

frikkievb
  • 481
  • 3
  • 11
0

Got it working... it was too difficult to change all $db->query calls in the existing system so here is the working example of what I did:

$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;
}

usage:

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

and use this in your page HTML

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