Reputation: 2097
in my PHP MySQL class, each time I run a query I'm storing it inside a public var, so that I can print all queries at the end of a script to debug how many i'm doing on each page. As well as ensure they're what I want them to be doing.
My problem, is that not all of the queries seem to be showing up. I think it's due to how I'm using my class.
Here's a snippet from the class:
class db_mysql extends PDO
{
protected static $instance;
public $stmt;
// the query counter
public $counter = 0;
// store all the queries for debugging
public $debug_queries = '';
public function __construct()
{
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false, // allows LIMIT placeholders
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8mb4'
];
parent::__construct("mysql:host=".DB['DB_HOST_NAME'].";dbname=".DB['DB_DATABASE'],DB['DB_USER_NAME'],DB['DB_PASSWORD'], $options);
}
// a classical static method to make it universally available
public static function instance()
{
if (self::$instance === null)
{
self::$instance = new self;
}
return self::$instance;
}
// the most basic query
public function run($sql, $data = NULL)
{
try
{
$this->stmt = $this->prepare($sql);
$this->stmt->execute($data);
$this->debug_queries .= '<pre>' . $this->replaced_query($sql, $data) . '</pre>';
return $this;
}
catch (PDOException $error)
{
$trace = $error->getTrace();
error_log('SQL ERROR ' . $error->getMessage());
die('SQL Error');
}
}
So then inside any other class, I can do this:
class test
{
private $dbl;
function __construct()
{
$this->dbl = db_mysql::instance();
$this->dbl->run("some update query");
}
My problem, is that it appears any queries done inside class "test" don't get added to the $debug_queries?
Upvotes: 0
Views: 36
Reputation: 2097
Turns out it was because when I'm accessing it as static from another class (like "test"), it doesn't add it to the non-static var.
Changing
public $debug_queries = '';
to
public static $debug_queries = '';
Along with adjusting this:
$this->debug_queries .= '<pre>' . $this->replaced_query($sql, $data) . '</pre>';
To this:
self::$debug_queries .= '<pre>' . $this->replaced_query($sql, $data) . '</pre>';
Has solved it and they all now show up no matter how it's called.
Upvotes: 1