Reputation: 69
Ok, similar questions has been asked and answered before. However, I want to count prepared queries as well. I thought I could just use the prepare() function to increment the query count but that provided me some questionable results. Right now, it's telling me 10 queries are being executed... Generally I only use prepared statements unless the data is static or cannot be modified in anyway.
I found this code from another question that was identical to this. Except that the code only was counting queries that were executed using the query() and exec() functions. I tried to modify it but as I said before it isn't counting any prepared queries but the queries are still executed and return results...
class PDOEx extends PDO
{
private $queryCount = 0;
public function query($query)
{
++$this->queryCount;
return parent::query($query);
}
public function exec($statement)
{
++$this->queryCount;
return parent::exec($statement);
}
public function execute($args = null)
{
++$this->queryCount;
if (!is_array($args)) {
$args = func_get_args();
}
return parent::execute($args);
}
public function GetCount()
{
return $this->queryCount;
}
}
I just want to say thanks in advance. Please, if you can point me in the right direction it would be much appreciated, thanks!
Upvotes: 2
Views: 333
Reputation: 2877
The reason prepared queries aren't being counted is because it returns a PDOStatement, which is different than PDO. You could just ask the database how many queries were run on a given session, so as long as you don't keep create new \PDO
objects then the result will be correct. Keep in mind even that query is counted as a query, so if you want to exclude it subtract 1 from the value.
Code
$db = new \PDO('mysql:host=127.0.0.1;dbname=sandbox', 'localuser', 'password');
$db->query('SELECT * FROM user WHERE id = 5');
$db->query('UPDATE user SET name = 'Demo' WHERE id = 5');
$db->query('DELETE FROM user WHERE id = 5');
echo $db->query('SHOW SESSION STATUS LIKE "Questions"')->fetchColumn(1);
Output
4
Upvotes: 1