How can classes and functions be utilized to track and count MySQL queries in PHP scripts?

To track and count MySQL queries in PHP scripts, you can create a class that extends the PDO class and override the query method to keep track of the queries being executed. You can then create a function to increment a counter every time a query is executed.

class CustomPDO extends PDO {
    private $queryCount = 0;

    public function query($query) {
        $this->queryCount++;
        return parent::query($query);
    }

    public function getQueryCount() {
        return $this->queryCount;
    }
}

// Usage example
$db = new CustomPDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

$db->query('SELECT * FROM users');
$db->query('INSERT INTO users (name) VALUES ("John")');

echo 'Total queries executed: ' . $db->getQueryCount();