开发者

How to modify a mysql_pconnect function in order to count queries

I have this code:

$hostname = "localhost";
$database = "listings";
$username = "joe";
$password = "1234";

$my_connection = mysql_pconnect($hostname, $username, $password) or trigger_error(mysql_error(),E_USER_ERROR);

How could I modify the function $my_connection so that it increases a variable like $total_qu开发者_开发百科eries and THEN it does the normal mysql_pconnect() thing and of course return the same thing ? The purpose is to be able to print in site footer: "Total queries: x".


You don't have to change the mysql_pconnect() call in order to calculate the total number of queries. Actually, you don't need to create new mysql connection before each query - if you are using the same MySql server all the time - you can (and in most cases you should) use only one connection. Back to your problem: if you want to calculate the total number of queries - create a function (or a MySQL-wrapper class), and use it for each query. In this case you will be able to find out the total number of queries. Here's the mock-up of such a class:

class MySQLWrapper
{

private $_link;
private $_totalQueries;

/**
* Connects to the database server
*
* @param string $hostname
* @param string $username
* @param string $password
*
*/
public function connect($hostname, $username, $password) {
     if (is_null($this->_link)) {
         $this->_link = mysql_pconnect($hostname, $username, $password);
     }
}

/**
* Performs query
*
* @param string $sql
* @return resource
*/
public function query($sql) {
    $this->_totalQueries++;
    return mysql_query($sql, $this->_link);
}

/**
* Returns count of queries made
* @return int
*/
public function getTotalQueryCount() {
    return $this->_totalQueries;
}
}

Thus, to find out the total number of queries made you can call getTotalQueryCount() method.

Note, this is only a mock-up of the real class, the actual code may be different, but I think you got the idea.


You need to create an abstraction layer for your database connection/query execution. You really want to abstract it anyway so you have centralized error handling.

For example, if you create you own class that has connect and execute functions, then you can add any code you want in them, like query counting. You can even have your execute function check if the database connection is active and establish a connection if one isn't. Your mysql_pconnect can then be part of the query execution function.

As an aside, persistent connections should not be used unless you have specific reasons to use them over regular connections. It's kind of counterintuitive. http://php.net/manual/en/features.persistent-connections.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜