Hi, thanks for the reply.
I am using singleton way so it doesnt create a new database connection / object each time i need to query the database? Is there a better way of achieving this.
In the end I would like a database class that has a query method that I can use for each time I need to pull back results.
so for example I need the query method to be dynamic and allow a return of an array, I then need to know the best way of allowing me to dynamically handling this array (maybe with another database method).
I can do the following but if you look at the index page you will see that I need to store the returned array in a variable first then echo the variable with the array element. Looks a bit messy, is there a way to do this in a one liner?
Database class:
<?php
class Database
{
private static $dbInstance;
private $hostname;
private $username;
private $password;
private $database;
private function __construct()
{
$this->hostname = 'localhost';
$this->username = 'user';
$this->password = 'pass';
$this->database = 'test';
mysql_connect($this->hostname, $this->username, $this->password);
mysql_select_db($this->database);
}
public static function getDBInstance()
{
if (!self::$dbInstance)
{
self::$dbInstance = new Database();
}
return self::$dbInstance;
}
public function query($q)
{
return mysql_query($q);
}
}
?>
person class:
<?php
require_once('Database.php');
class person
{
public function getName($id)
{
$con = Database::getDBInstance();
$query = $con->query("select name from data where id = ".$id);
return mysql_fetch_assoc($query);
}
}
?>
index page:
<?php
require_once('person.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<body>
<?php
$person = new person();
$name = $person->getName(1);
echo $name['name'];
echo "<br />";
$name = $person->getName(2);
echo $name['name'];
?>
</body>
</html>