Hi,
I really wanted to get an idea of the way people handle their database connections and queries in PHP5.
I’m not really sure of the best approach.
What I’m doing at the moment is defining a singleton class to hold a PDO connection object, then defining a class with static methods for querying:
[code=php]
// Singleton class to hold db connection
class db
{
private static $_instance;
private static $_connection;
private static $_user=’myUser’;
private static $_pass=’myPass’;
private static $_host=’myHost’;
private static $_dbname=’myDB’;
protected final function __construct()
{
try
{
self::$_connection = new PDO(‘mysql:host=’.db::$_host.’;dbname=’.db::$_dbname, db::$_user, db::$_pass, array(PDO::ATTR_PERSISTENT => true));
}
catch (PDOException $e)
{
print “Error!: ” . $e->getMessage() . “<br/>”;
die();
}
}
public static function getInstance()
{
if (!self::$_instance instanceof self)
{
self::$_instance = new self;
}
return self::$_instance;
}
public function con()
{
return self::$_connection;
}
}
[code=php]
// Data Access Layer
class dal
{
private static function getResults($query)
{
return db::getInstance()->con()->query($query,PDO::FETCH_ASSOC);
}
private static function getResult($query)
{
return db::getInstance()->con()->query($query,PDO::FETCH_ASSOC)->fetch();
}
public static function getProducts()
{
$sql = ‘select * from products’;
return self::getResults($sql);
}
}
What do you think of this approach? Is there a better way?
Thanks