Count number of queries per page request? - php

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();

Related

PHP OOP with mySQLi fetch

I am relatively new to PHP OOP and i know that there are numerous questions here on SO, but none of them seam to be pointing me in the right direction. I have created the class user, and I am calling this in another file.
I am trying to get the method 'reset' to call up 'connect', connect to the mysql db and then query it and set various properties to the row contents.
I am receiving no errors but for some reason it is not feeding the properties any data from the database.
I have tried placing the mySQL connect in the reset method, just to see if the variables cannot be passed between methods. But still no joy.
Can anyone point me in the right direction?
class user(){
public function reset(){
$this->connect();
$sql ='SELECT * FROM users WHERE user_id="'.$user_id.'"' ;
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$this->user_name=$row['dtype'];
$this->user_id=$row['user_id'];
$this->atype=$row['atype'];
$this->user_email=$row['user_email'];
$this->group1=$row['group1'];
$this->group2=$row['group2'];
$this->group3=$row['group3'];
$this->group4=$row['group4'];
$this->group5=$row['group5'];
$this->group6=$row['group6'];
}
// Test that these properties are actually being echoed on initial file... it is
// $this->user_name = "john";
// $this->user_email = "john#gmail.com";
// $this->dtype = "d";
// $this->atype = "f";
}
public function connect(){
//GLOBALS DEFINED IN INDEX.PHP
if ($db_open !== true){
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno())
{
$debug_system .= 'Error on user.php: ' . mysqli_connect_error().'<br\/>';
} else {
$db_open = true;
$debug_system .= 'user.php: user details grab successful. <br\/>';
}
}
}
}
If you are relatively new to PHP OOP, it is strongly recommended not to mess with awful mysqli API but learn quite sensible PDO first, and only then, making yourself familiar with either OOP and prepared statements, you may turn to mysqli.
Nevertheless, there shouldn't be no function connect() in the class user. You have to have a distinct db handling class, which instance have to be passed in constructor of user class
The problem lies in this line:
$sql ='SELECT * FROM users WHERE user_id="'.$user_id.'"' ;
At no point do you actually define $user_id. Presumably you actually mean $this->user_id.
$sql ='SELECT * FROM users WHERE user_id="'.$this->user_id.'"' ;
Better still would be to make full use of parameterized queries, which might look like this:
$sql ='SELECT * FROM users WHERE user_id=?' ;
You would then prepare the statement and bind the user ID, then execute the query:
$stmt = mysqli_prepare($sql);
mysqli_stmt_bind_param($stmt, $this->user_id);
mysqli_stmt_execute($stmt);
And then fetch the results:
while($row = mysqli_stmt_fetch($result))
As you can see, there is a whole load more to modern MySQL libraries. I'd advise you to do more research into how MySQLi and parameterized queries work (and perhaps PDO as well: it's a superior library) before you use them further. It will be worth the effort.

Utilizing an existing database connection in a function

In a file, I connect to the database (using PDO) and the resulting connection is called $db, so that queries I run would be something like
$db->query("SELECT money FROM bank_accounts");
However, if I put that line in a function, $db isn't defined so it doesn't work.
Obviously reconnecting to the database in each function isn't the best way to accomplish db calls in a function so how would I accomplish something like
function stealMoney($acctID) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
You need to use $db in a function.
And its not defined in the function, so definitely, $db is inaccessible/undefined to the function body.
There are two ways to deal it:
1) Pass $db as an argument to the function.
So, the function body becomes:
function stealMoney($acctID, $db = NULL) {
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
}
And the function call:
stealMoney($acctID, $db);
2) Use global:
In this case, you can use $db as a global.
So, the function body becomes:
function stealMoney($acctID) {
global $db;
$db->query("SELECT money FROM bank_accounts WHERE accountID = $acctID");
So that, your function will read this variable from outside and can access it.

Efficiently use mysqli in object oriented setting

I have come to the conclusion that using mysqli in an OO approach is better than a procedural approach. (Source: Why is object oriented PHP with mysqli better than the procedural approach?). But I'm not quite sure if what I am doing is really all that more efficient than what I was doing before.
I have a function that runs sql queries. This is what my block of code looked like:
Database connection:
function connectDB(){
$con = mysqli_connect(server, username, password, database);
return $con;
}
Query function:
function executeQuery($payload){
$con = connectDB;
$result = mysqli_query($con, $payload);
return $result;
}
As you can see, that's not very efficient because I'm creating a new database connection every time executeQuery is called. So I figured I'd try it using OOP.
Database connection (OOP):
function connectDB(){
$con = new mysqli(server, username, password, database);
return $con;
}
Database query (OOP):
function executeQuery($payload){
$con = connectDB();
$result = $con->query($payload);
return $result;
}
Now to me, it seems that I am obviously doing something wrong. Each time a query is called I am re-instantiating the mysqli class and I assume that mean's that I am making another database connection.
So how do I do this properly and efficiently?
So how do I do this properly and efficiently?
This really has nothing to do with using MySQLi in a procedural versus OOP way.
What this has to do with is the following line:
$con = connectDB();
This will recreate the database connection on every query. Which, as you noted, is not efficient.
There are many ways to solve this. For example:
Use the mysqli class directly.
Pass $con to executeQuery() (Dependency Injection)
Create a DB class with both connectDB() and executeQuery().
I usually use mysqli directly as I see no reason to wrap the native class. I create the connection object globally (in a config file) and use Dependency Injection when other objects/functions need it.
Although your procedural approach can be solved pretty easily
function connectDB(){
return mysqli_connect(server, username, password, database);
}
function executeQuery($payload){
static $con;
id (!$con)
{
$con = connectDB();
}
return $con->query($payload);
}
an OOP approach would be indeed better. I am not an OOP pro, but you can take a look at my approach which at least using encapsulation to hide all the dirty job inside and provide concise methods to get the data already in desired format like this:
// to get a username
$name = $db->getOne('SELECT name FROM table WHERE id = ?i',$_GET['id']);
// to get an array of data
$data = $db->getAll("SELECT * FROM ?n WHERE mod=?s LIMIT ?i",$table,$mod,$limit);
// to get an array indexed by id field
$data = $db->getInd('id','SELECT * FROM ?n WHERE id IN ?a','table', array(1,2));
// to get a single dimensional array
$ids = $db->getCol("SELECT id FROM tags WHERE tagname = ?s",$tag);
// a simple code for the complex INSERT
$data = array('offers_in' => $in, 'offers_out' => $out);
$sql = "INSERT INTO stats SET pid=?i,dt=CURDATE(),?u ON DUPLICATE KEY UPDATE ?u";
$db->query($sql,$pid,$data,$data);
As a solution for your exact problem : "You do not want to instantiate a new MySQL connection for each time a query is executed" ,
Well, we can think about the following :
You need to make your connection variable ($con) in GLOBAL scope, such that when accessed through any function you can grab THAT variable you set before, not instantiate a new one.
we can do this using keyword "global" , as following :
The connection function :
function &connectDB(){
global $con;
if(empty($con)) {
$con = new mysqli(server, username, password, database);
}
return $con;
}
And for more performance , we avoid cloning/copying the connection variable/resource by using reference function ( &connectDB ),
Query Execution function
Now we've set the connection function in a flexible way , to set the queryExecution function , we can use more than one solution :
First solution :
function executeQuery($payload){
$con = &connectDB(); // do not forget the () , it's good practice
return $con->query($payload);
}
In this solution we made use of "reference" , so the expression :
$con = &connectDB();
will set the variable $con as a reference/shortcut for global $con (i.e : just pointing to the global variable $con)
or
Second solution :
function executeQuery($payload){
global $con;
return $con->query($payload);
}
but for the second solution : Function "connectDB()" MUST be called at least once before any calling to "executeQuery()", In order to make sure that there a connection has been established with the database,
Keep in mind that, according to this solution , calling "connectDB()" more than once will not create more than one connection , once it is called , connection is created, if called again it will return the PREVIOUSLY created connection.
Hope it helps :)
by the way : stay with the OOP approach for database connection , it has much more benefits over the procedural ways,
& I recommend using PDO, it is much more portable.

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_queries 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

simple db query function

I want to be able to call a query function and based on the results they are put into an object that I can call outside the function. This is what I have:
<?php
function query($sql) {
global $r;
$database = "theatre";
$db_conn = pg_connect ("host=localhost port=5432
dbname=$database user=postgres");
if (!$db_conn): ?>
<h1>Failed connecting to postgres database <?php echo $database;?></h1>
<?php
exit;
endif;
$ep = pg_query ($db_conn, $sql);
while ($r = pg_fetch_object ($ep)) {
}
pg_free_result($ep);
pg_close($db_conn);
}
query('select * from test');
echo $r->fname;
I don't want to hardcode any column names into the function. So fname is an example but it will be dynamic based on the query. I have a while loop but not sure what to put in it.
Value returned by function pg_fetch_object is already an object, so no need to loop through results. Just return it:
return pg_fetch_object ($ep);
Then just use the returned results without referring to this awkward global variable $r.
$r = query('select * from test');
echo $r->fname;
Also, no need to free the resource with pg_free_result. It gets freed automatically at end of scope it exists within (that is current function in this case). Calling pg_close may also slow down your script, as the connection will have to be recreated anew next time you call the function. I'd suggest storing connection in local static variable and not closing it at all - it will be closed automatically.
function query($sql) {
$database = "theatre";
static $db_conn;
if (!$db_conn) {
$db_conn = pg_connect ("host=localhost port=5432 dbname=$database user=postgres");
}
...
As a long term solution I'd recommend researching subject of Object-Relational Mapping and learning one of available ORM-ish tools (i.e. Zend Db Table, Doctrine, Propel, or one of existing implementations of ActiveRecord pattern).

Categories