UPDATED: Changed code to the now working class code using PDO instead of deprecated methods
The original question was answered and the prob
In order for your class to operate statically, you need to do a few things.
First, make the connection static, eg
private static $connection;
Secondly, why all the underscores?
define('DB_HOST', 'localhost');
define('DB_NAME', 'your_db_name');
define('DB_USER', 'username');
define('DB_PASS', 'password');
Also, why use class constants at all? Just use the constants you've already defined.
Third, lose the constructor. You cannot expect to create an instance of this class and use it statically. I would go for a lazy-load approach for the connection
private static function getConnection() {
if (self::$connection === null) {
$dsn = sprintf('mysql:host=%s;dbname=%s;charset=utf8',
DB_HOST, DB_NAME);
self::$connection = new PDO($dsn, DB_USER, DB_PASS, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
));
}
return self::$connection;
}
Then, your public methods would call this method internally. I'll also flesh out your dbDataArray
method to show you how to return an associative array
public static function dbDataArray($query, $params = array()) {
$stmt = self::getConnection()->prepare($query);
$stmt->execute($params);
return $stmt->fetchAll();
}