Hello. I am working with an example in a MySQL performance book, but it involves PHP. I cannot get the code example to work.
It always reports:
Fatal error: Call to a member function query() on a non-object in C:\wamp\www\page1.php on line 15
Here is the code:
PHP Code:
<?php
class mysqlx extends mysqli {
function query($query, $resultmode) {
$timer = Timer::getInstance();
$timer->startTime('MySQL');
$res = parent::query($query, $resultmode);
$timer->stopTime('MySQL', "Query: $query\n");
return $res;
}
}
/*
* Class DBQueryLog logs profiling data into the database
*/
class DBQueryLog{
function logProfilingData($data) {
$table_name = "logs.performance_log_" . @date("ymd");
$query = "INSERT DELAYED INTO $table_name (ip, page, utime,
wtime, stime, mysql_time, sphinx_time, mysql_count_queries,
mysql_queries, user_agent, referer) VALUES (.. data ..)";
$res = $this->mysqlx->query($query);
// Handle "table not found" error - create new table for each new day
if ((!$res) && ($this->mysqlx->errno == 1146)) { // 1146 is table not found
$res = $this->mysqlx->query(
"CREATE TABLE $table_name LIKE logs.performance_log_template");
$res = $this->mysqlx->query($query);
}
}
// This helper function implements the Singleton pattern
function getInstance() {
static $instance;
if(!isset($instance)) {
$instance = new Timer();
}
return($instance);
}
}
As currently coded, there is no instance of your mysqlx class in the DBQueryLog class.
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
You may want a __construct() method in the class to instantiate it:
PHP Code:
class ClassName
{
protected $mysqlx;
public function __construct()
{
$this->mysqlx = new mysqlx();
}
// rest of class...
}
However, since mysqlx extends MySQLi, which normally gets the DB connection credentials passed to its constructor, you might be better off instantiating it in your main script, then passing that instance as a parameter to the constructor:
PHP Code:
class ClassName
{
protected $mysqlx;
public function __construct(mysqlx $mysqlx)
{
$this->mysqlx = $mysqlx;
}
// rest of class...
}
$mysqlx = new mysqlx($dbhost, $dbuser, $dbpass, $dbname);
$foo = new ClassName($mysqlx);
"Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
~ Terry Pratchett in Nation
Bookmarks