简体   繁体   中英

Count number of queries per page request?

I need to know how many sql queries are being executed per page request. As the site is already done and I am just running optimization analysis, I would prefer if any solution offered doesnt require that i change the entire website structure.

I use a single connection to send all queries to the MySQL database:

define('DATABASE_SERVER', '127.0.0.1');
define('DATABASE_NAME', 'foco');
define('DATABASE_USERNAME', 'root');
define('DATABASE_PASSWORD', '');

$DB_CONNECTION = new mysqli(
    DATABASE_SERVER,
    DATABASE_USERNAME,
    DATABASE_PASSWORD,
    DATABASE_NAME,
    3306
);

Then to execute a query i use:

$query = "SELECT * FROM `sometable`";
$queryRun = $DB_CONNECTION->query($query);

Is there a way to count how many queries have been sent and log the answer in a text file just before php closes the connection?

You can extend the mysqli object and override the query method:

class logging_mysqli extends mysqli {
    public $count = 0;
    public function query($sql) {
        $this->count++;
        return parent::query($sql);
    }
}

$DB_CONNECTION = new logging_mysqli(...);

One of the best ways would be to run a log function inside your $DB_CONNECTION->query() .

That way you can either log each individual query to a db table, or perform basic test on query speed and then store this, or just increment the count (for number of queries) and store this.

Create class extending mysqli , make $DB_CONNECTION object of that class and do your statistics in your implementation of query() method. Eventually it shall call parent::query() to do real job.

Create a proxy that you use instead of mysqli directly...

class DatabaseCounter {
    private $querycount = 0;
    private $mysqli = null;

    // create mysqli in here in constructor


    public function query(...) {
        $this->queryCount++;
        $this->mysqli->query(...);
    }
}

$DB_CONNECTION = new DatabaseCounter();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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