Reputation: 4377
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?
Upvotes: 0
Views: 2607
Reputation: 13972
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();
Upvotes: 0
Reputation: 75619
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(...);
Upvotes: 4
Reputation: 91
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.
Upvotes: 1
Reputation: 75629
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.
Upvotes: 0