Hello,
Salathe was helping me a bit with this script I'm coding, and I figured it would be best if I just used a database class for this script, as it might be helpful to us in the future. The problem is, when I use
$db->query('query'); it says that
query() is an undefined method, when it clearly is.
Now, I'm not even sure if the way I'm going about using the class is the best way, so if someone could make some suggestions, that would be helpful.
Database.class.php
PHP Code:
<?php
class Database {
private $szHost;
private $szUser;
private $szPass;
private $szName;
private static $pInstance;
private function __construct($szHost, $szUser, $szPass, $szName) {
$this->szHost = $szHost;
$this->szUser = $szUser;
$this->szPass = $szPass;
$this->szName = $szName;
mysql_connect($this->szHost, $this->szUser, $this->szPass)
or die('Could not connect to the database.<br />'."\n".mysql_error());
mysql_select_db($this->szName)
or die('Could not connect to the database.<br />'."\n".mysql_error());
}
public static function getInstance($szHost, $szUser, $szPass, $szName) {
if (!self::$pInstance) {
self::$pInstance = new Database($szHost, $szUser, $szPass, $szName);
}
return self::$pInstance;
}
public function query($szQuery) {
$pQuery = mysql_query($szQuery);
return $pQuery;
}
}
?>
Excerpt of Categories.class.php
PHP Code:
<?php
class Categories {
public $cat_id;
public $cat_name;
function list_cats($szBefore = '', $szAfter = '') {
global $settings, $db;
$pQuery = $db->query(" SELECT *
FROM categories");
$aResult = mysql_fetch_array($pQuery);
$szOutput .= $szBefore;
$szOutput .= '<a href="'.$settings->info('site_url').'" title="'.$aResult['name'].'">'.$aResult['name'].'</a>';
$szOutput .= $szAfter."\n";
echo $szOutput;
}
}
?>
Excerpt of global.php
PHP Code:
<?php
require_once 'config.php';
require_once 'database.class.php';
function __autoload($szClassName) {
require_once strtolower($szClassName).'.class.php';
}
global $db, $settings, $cat;
$db = Database::getInstance($dbHost, $dbUsername, $dbPassword, $dbName);
$settings = new Settings;
$cat = new Categories;
?>
Now, the main problem is when I call
$cat->list_cats(); It spits out:
Code:
Fatal error: Call to undefined method Database::query() in C:\xampp\htdocs\PHP\VW\includes\categories.class.php on line 10
and I'm not sure why. Does it have to do with how I'm using the globals to gain access to the class? I'm new to the whole database-inclusion bit, so any help would be great.
Thanks,
Andrew