I am using below code for database connection
class Database extends PDO{
function __construct(){
try {
parent::__construct(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
} catch(PDOException $e){
Logger::newMessage($e);
logger::customErrorMsg();
}
}
}
every thing like login , fetching data was working fine . Now suddenly I am having a exception error message
Message: SQLSTATE[08004] [1040] Too many connections
Code: 1040
How to fix this error ?
I have a model class there I am creating new database.
class Model {
protected $_db;
public function __construct(){
//connect to PDO here.
$this->_db = new Database();
}
}
and every model I make , I am extending from model class.
Because your Model class instantiates a new Database object in its constructor, each time you instantiate a Model (or any class extending it), you are in effect opening a new database connection. If you create several Model objects, each then has its own independent database connection, which is uncommon, usually unnecessary, not a good use of resources, but also actively harmful as it has used up all the server's available connections.
For example, looping to create an array of Model objects:
// If a loop creates an array of Model objects
while ($row = $something->fetch()) {
$models[] = new Model();
}
// each object in $models has an independent database connection
// the number of connections now in use by MySQL is now == count($models)
Use dependency injection:
The solution is to use dependency injection and pass the Database object into the Model::__construct() rather than allow it to instantiate its own.
class Model {
protected $_db;
// Accept Database as a parameter
public function __construct(Database $db) {
// Assign the property, do not instantiate a new Database object
$this->_db = $db;
}
}
To use it then, the controlling code (the code which will instantiate your models) should itself call new Database() only once. That object created by the controlling code must then be passed to the constructors of all models.
// Instantiate one Database
$db = new Database();
// Pass it to models
$model = new Model($db);
For the use case where you actually need a different independent database connection for a model, you can hand it a different one. In particular, this is useful for testing. You can substitute a test database object, or a mock object.
// Instantiate one Database
$db = new Database();
$another_db = new Database();
// Pass it to models
$model = new Model($db);
$another_model = new Model($another_db);
Persistent connections:
As mentioned in the comments, using a persistent connection is possibly a solution, but not the solution I would recommend. PDO will attempt to reuse an existing connection with the same credentials (as all yours will have), but you don't necessarily want the connection to be cached across script execution. If you did decide to do it this way, you need to pass the attribute to the Database constructor.
try {
// Set ATTR_PERSISTENT in the constructor:
parent::__construct(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS, array(PDO::ATTR_PERSISTENT => true));
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
}
The relevant documentation is here: http://php.net/manual/en/pdo.connections.php#example-950
Singleton solution:
Using a singleton pattern (also not recommended), you could at least reduce this to a search/replace in the model code. The Database class needs a static property to keep a connection for itself. Models then call Database::getInstance() instead of new Database() to retrieve the connection. You would need to do a search and replace in the Model code to substitute Database::getInstance().
Although it works well and isn't difficult to implement, in your case it would make testing a little more difficult since you would have to replace the entire Database class with a testing class of the same name. You can't easily substitute a test class on an instance by instance basis.
Apply singleton pattern to Database:
class Database extends PDO{
// Private $connection property, static
private static $connection;
// Normally a singleton would necessitate a private constructor
// but you can't make this private while the PDO
// base class exposes it as public
public function __construct(){
try {
parent::__construct(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8'");
} catch(PDOException $e){
Logger::newMessage($e);
logger::customErrorMsg();
}
}
// public getInstance() returns existing or creates new connection
public static function getInstance() {
// Create the connection if not already created
if (self::$connection == null) {
self::$connection = new self();
}
// And return a reference to that connection
return self::$connection;
}
}
Now you would need to change only the Model code to use Database::getInstance():
class Model {
protected $_db;
public function __construct(){
// Retrieve the database singleton
$this->_db = Database::getInstance();
}
}
Related
What's the difference between a class with constructor and class without when calling a function in this code? below is my example code
Class w/ Constructor:
class DatabaseConnection
{
public $database_host = "";
public $database_name = "";
public $database_username = "";
public $database_password = "";
public function __construct( $database_host, $database_name, $database_username, $database_password )
{
$this->$database_host = $database_host;
$this->$database_name = $database_name;
$this->$database_username = $database_username;
$this->$database_password = $database_password;
}
public function connect_database()
{
$database_connection = null;
try {
$database_connection = new PDO( "mysql:host={$database_host};
dbname={$database_name}",
$database_username,
$database_password );
$database_connection->setAttribute( PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $pdo_exception ) {
trigger_error( $pdo_exception,
E_USER_ERROR );
}
return $database_connection;
}
}
Class without constructor:
class DatabaseConnection
{
public function connect_database( $database_host, $database_name, $database_username, $database_password )
{
$database_connection = null;
try {
$database_connection = new PDO( "mysql:host={$database_host};
dbname={$database_name}",
$database_username,
$database_password );
$database_connection->setAttribute( PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $pdo_exception ) {
trigger_error( $pdo_exception,
E_USER_ERROR );
}
return $database_connection;
}
}
Call a function in a class that has constructor:
$db = new DatabaseConnection( "localhost", "dbname", "username", "password" )
$db->connect_database();
Call a fucntion in a class that has no constructor:
$db = new DatabaseConnection();
$db->connect_database( "localhost", "dbname", "username", "password" );
Technically, almost everything that is done in a constructor could also be done within other functions. There are advantages in using constructors though. One huge benefit I think lies within the semantics.
semantics of a constructor
When I say something like $house = new House(), I do expect to have a house. I would not expect to have a skeleton of a house, with all the walls and the roof missing. I would not expect, that I'm required to call $house->build() or $house->complete() after I created it. Because if I need to call that, it wasn't a house, it was a template of a house or a design or whatever.
The same logic goes for your DatabaseConnection. If I have to call connect_database() (in either of your two cases), I would argue, that the DatabaseConnection wasn't a database connection before, so what does new DatabaseConnection([args]) actually mean in your case? It creates an object of the class DatabaseConnection, that can - after creation - be used to create a database connection. So, technically, it's a DatabaseConnector.
Constructors have many advantages, mainly when you don't have any influence on which functions get called on it. Let's for example assume, that you're writing a database connector for a function called getBlogEntry, because your blog is super dynamic and stuff.
var $connectionString = "mysql:localhost;someparams";
function getBlogEntry($request) {
global $connectionString; // global is bad, but space is precious
$db = new DatabaseConnection($connectionString);
$db->query([query to fetch the current blog entry])
}
The point here is, you don't want to call a different connect function after creating the object. When the object exists, the connection should exist. Your API should be as clear as possible. Technically there might be no difference between doing the work in the constructor or in another function, but there sure as hell is a semantic difference. You should have a good argument not doing something in a constructor that's necessary to actually use all the functions of an object.
answer to the question
To actually answer your question. The class with constructor has 4 member variables, which you can be sure that whoever created an object of that class has provided those values. Setting those values can of course also be done by your connect_database. For the connect_database it doesn't make a big difference if it uses member vars or params (there is of course a small difference, accessing member vars is different than params, but that should not be your concern - especially in this case).
However, in your specific code example, you wouldn't need the DatabaseConnection class at all! You could just define the (second) function and be done with it.
It is not required to explicitly define a constructor; however, all classes must have a constructor, and a default empty constructor will be generated if you don't provide any. If you create constructor with parameters it simply passes them to the fields in the class.
I have a PDO connection in my database class and recently I have been using this as an extension for other classes i.e. class Users extends Database this allows me to always keep a Database connection without having to have a function in my Users class.
However somebody pointed out that I shouldn't be doing this as its bad practice, why exactly is this bad practice? And how can I connect to my database class in my user class without extending?
Currently I have the call to the database inside my viewall() function I tried to put this in a __construct() function however it insisted on having parameters
I've tried the below code however I get the error message as follows:
Fatal error: Call to undefined method Database::prepare() in E:\xampp\htdocs\attendance\class.Register.php on line 13
Any ideas on how I can call on my database?
This is my code:
class.Connect.php
<?php
// Database connection PDO
class Database {
public function __construct() {
// Connection information
$host = 'localhost';
$dbname = 'attendance';
$user = 'root';
$pass = '';
// Attempt DB connection
try
{
$this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Successfully connected to the database!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function __destruct()
{
// Disconnect from DB
$this->pdo = null;
//echo 'Successfully disconnected from the database!';
}
}
?>
class.Register.php
<?php
require 'class.Connect.php';
class Register {
public function viewall() {
$pdo = new Database();
$stmt = $pdo->prepare('SELECT * FROM users');
$stmt->execute();
$stmt->fetch();
}
}
$run = new Register();
$run->viewall();
?>
Simple rule of thumb: if a class extends another, then that class is that parent class (only slightly altered or extended). You can pass this child class instead of the parent class. Example:
class Foo { }
class Bar extends Foo { }
function baz(Foo $foo) { }
baz(new Bar);
This works, baz() expects a Foo but also accepts a Bar, because Bar is a Foo.
Now, is your Users a Database? No. Your users are not a database. Your users use a database. If at all, you should use composition:
class User {
protected $database;
public function __construct(Database $database) {
$this->database = $database;
}
}
A class should be what its responsibilities are. The responsibility of a user management class is to manage user data. Part of that may involve talking to a database, but that doesn't mean the user management class is a database. If User extends Database, that means it can do everything the Database class can do (and more). That means you could use the User class everywhere instead of the Database class, and that doesn't make any sense. Keep responsibilities separate.
Now, it's still debatable whether that is the right structure or not, but it goes into the right direction. But you may really want to have a User class, which represents one user. You then have a UserManager or UserORM or UserStorage or whatever, which is concerned with retrieving and storing User objects in a database. This class in turn uses a Database to do just that. That keeps responsibilities clear and separated. The User class represents user data, the Database class interacts with the database, the UserORM/Manager/whatever in the middle negotiates between the two.
There may be several ways to connect to a database such that you have a connection everywhere in your application. For a good practice, you can do it easily by using another class which can handle your datbase operations and you extend all your classes which require db operations from that class.
First change your Database class a little and pass the arguments for database connection as below :
<?php
// Database connection PDO
class Database {
public function __construct($host, $dbname, $user, $pass) {
// Connection information
// Attempt DB connection
try
{
$this->pdo = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Successfully connected to the database!';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
public function __destruct()
{
// Disconnect from DB
$this->pdo = null;
//echo 'Successfully disconnected from the database!';
}
}
?>
Now create another class lets call it ObjectModel as below
class ObjectModel
{
protected $db
public function __construct()
{
$this->db = new Database($host, $dbname, $user, $pass) //ofcourse you can get the db connections details and database name from a config file
}
// you can have more db operations functions like insert, update, delete etc
}
SO the ObjectModel class will be handling all your CRUDs and other db operations and running queries also. Now if you want to use the $db object, you can use it directly in the ObjectModel class and also in child classes of OBjectModel as below:
class Users extends ObjectModel
{
public function getUsers()
{
//$this->db-> whatever operation you want to do you can do it using this db object
}
}
Remember that the ObjectModel has an object of the Database class called $db, so if your Database class is using PDO, then your ObjectModel $db object will have all those operations ie, using PDO.
I hope this will help for you also, as i am using such ObjectModel class for my classes and it saves me a lot of time to write codes again and again :) .
Happy Coding ;)
Is extending classes good practice?
Well, yes, if you do it right and for the right reason.
The concept of inheritance (class extensions) in object-oriented programming is working like the same as if you had those objects in real world.
In real world when you use the world Car, then by convention you usually mean all the cars and you consider common attributes in it, for example, wheels, engine, steering, throttle, brake etc.
but there are some cars that have those attributes and some additional too, for example a Fire Truck Car also has some extra attributes as a ladder attached, some tubes for water throwing etc.
The same could be considered for the "behavior" of some objects, for example, a car can move, and by that we mean you have wheels rotation on the road in order to move (modeled by Car move method).
Also, a firetruck may have an extended behavior, for example can move up and down the ladder it has. This can be modelled by having the method moveLadder() in the FireTruckCar class.
If you wanted to represent these concepts in PHP classes (OOP), you could do:
class Car {
protected $wheels;
protected $engine;
//Rest attributes of Car.
public function __construct($wheels, $engine) {
$this->wheels = $wheels;
$this->engine = $engine;
//Initialize more attributes.
}
function move(){
$this->wheels->rotate();
}
//.....
}
class FireTruckCar extends car{
//Additional Attributes.
//The attributes of Car class belong to this
//one too and are accessible as private.
protected $ladder;
protected $tubes;
public function __construct($wheels, $engine, $ladder, $tubes) {
//Call the parent constructor, to initialize parent attributes
parent::__construct($wheels, $engine);
$this->ladder = $ladder;
$this->tubes = $tubes;
}
function moveLadder($direction){
$this->ladder->move($direction);
}
//...
}
Of course, there are many additional concepts in inheritance and generally OOP such as method overloading/overriding, abstract classed etc., but I am not goind to explain about them here as the point will be missed.I suggest you search for Object Oriented Programming Principles though and learn about them well.
I have a class called DB (class.pdo.php) that does all the handling on mysql queries using PDO and another class called user that I use to manage a login system.
My question relates to always having to instantiate the $db in every public function of users so I can use DB. Is this efficient? Shouldn't I be instantiating DB inside the __construct() of users?
This is my code
require_once("../../class.pdo.php");
class user {
private $db = null;
public function __construct(){
/* Empty? */
}
public function find_by_email($email){
$db = new db();
$db->query('SELECT * FROM users WHERE email = :email LIMIT 1');
$db->bind(':email',$email);
$result = $db->single();
return $result;
}
public function create($email,$password,$first_name,$last_name){
$db = new db();
$db->query("INSERT INTO users(email,password,first_name,last_name,created_at) VALUES (:email,:password,:first_name,:last_name,NOW())");
$db->bind(':email',$email);
$db->bind(':password',$password);
$db->bind(':first_name',$first_name);
$db->bind(':last_name',$last_name);
$result = $db->execute();
return $db->lastInsertId();
}
[more similar functions ommited]
Well, despite of some comments suggesting the use of the Singleton pattern, I totaly disagree in using it for this purpose.
Your application will not always use a single connection to just one database.
Let me show you how I'd do this:
class DbConnector {
private $dbh;
private $dsn;
public function __construct($dsn) {
$this->dsn = $dsn;
}
private function connect() {
if($this->dbh === null) {
$this->dbh = new PDO($this->dsn);
}
}
public function disconnect {
if($this->dbh !== null) {
$this->dbh = null;
}
}
public function query($sql) {
$this->connect();
//... do the rest
}
public function fetchAll($sql) {
$this->connect();
//... do the rest
}
public function insert($table, $values) {
$this->connect();
//... do the rest
}
public function update($table, $values, $cond) {
$this->connect();
//... do the rest
}
public function delete($table, $cond) {
$this->connect();
//... do the rest
}
}
class User {
private $dbConn;
public function __construct(DbConnector $dbConn) {
$this->dbConn = $dbConn;
}
public function create($email,$password,$first_name,$last_name){
$this->dbConn->query("INSERT INTO users(email,password,first_name,last_name,created_at VALUES (:email,:password,:first_name,:last_name,NOW())");
$this->dbConn->bind(':email',$email);
$this->dbConn->bind(':password',$email);
$this->dbConn->bind(':first_name',$email);
$this->dbConn->bind(':last_name',$email);
$this->dbConn->execute();
return $this->dbConn->lastInsertId();
}
// ...
}
Results:
No singleton used = testable.
Connection to the database is just openned when needed
Your connection is persistent. If you open and close connections in every method, you loose the capability of creating transactions.
What about using the Singleton pattern to create one object for the connection and use it everytime you need it, instead of creating new objects all the time?
I would do something similar with lazy loading: don't initiate in the constructor unless you're sure you actually need the connection every time an object is created but absolutly don't create a new object on each method call. Instead, save the resulting object into an object var which is checked on each method call and initiates the connection if missing.
class user {
protected $_db = null;
private function _init_db() { $this->_db = new XXX; }
public function create( $x, $y, $z ) {
if ( ! $this->_db ) $this->_init_db();
# use $this->_db ..
}
public function find_by_email( $x, $y, $z ) {
if ( ! $this->_db ) $this->_init_db();
# etc
}
}
This has the advantages of avoiding global static state (singletons..) and only creates the connection / object at the very last moment so you're sure you actually need it and it's not just a useless connection.
Speaking of efficiency, the main problem with your code is that it establishes new connection for the every method called. This one is indeed inefficient to the point of killing your database server. And it's incomparable to the other problem you have.
So, in general, you can have whatever way you want - either get somehow an instance of db class in the every function or use a class variable - but either way have to use single PDO instance throughout whole application.
Also I find your functions quite inefficient from the amount of code point of view, and would have optimized them this way
public function create($email,$password,$first_name,$last_name){
$sql = "INSERT INTO users(email,password,first_name,last_name,created_at) VALUES (?,?,?,?,NOW())";
$this->db->query($sql);
$result = $db->execute(func_get_args());
return $db->lastInsertId();
}
From a object point of view, I'd leave database instantiating within the methods, rather than an entire class.
Each method should only see the variables and data it needs, in order to perform its function.
For instance, a createUser() method would need to see variables or properties such as $username, $usergroupId, as well as $database etc.
However, you may have a function which is called randomPassword(), which generates a random password from numbers and letter.
This randomPassword() function doesn't need the database object and therefore, an already initialised database connection in the object scope would be wasteful.
It would be better only to create the new database object in methods that required it.
In addition, in my application, I don't create a new database connection each time I used new database. Instead, I've opted for a singleton PDO database object which keeps the connection active.
I can then just call the database object statically to retrieve an existing connection. Therefore, if, in the process of running my application I need to have 20 database objects, my application then only returns the same object, and the same connection.
I was reading this SO question:
PHP - multiple different databases dependency injected class
Top answer. I understand the concept behind using an Interface here, but I don't know how to use it. Here is what the top answer said, sorry if I'm not supposed to copy it here:
You should create an interface first for all the DB operations.
interface IDatabase
{
function connect();
function query();
...
}
Then have different driver classes implementing this interface
class MySQLDB implements IDatabase
{
}
class PGSQLDB implements IDatabase
{
}
This way you can easily use dependency injection.
class Test
{
private $db;
function __construct(IDatabase $db)
{
$this->db = $db;
}
}
You can call it as:
$mysqldb = new MySQLDB();
$test = new Test($mysqldb);
or
$pgsqldb = new PGSQLDB();
$test = new Test($pgsqldb);
What I don't understand is how to complete it in the class test and what I am passing to test. Where is my connection information going? I was hoping someone would help me complete this for a mysql connection or maybe pdo.
Your connection info would go in the MySQLDB class, so you could have something like this:
class MySQLDB implements IDatabase
{
private $pdo; // Holds the PDO object for our connection
// Or you can remove the parameters and hard code them if you want
public function __construct( $username, $password, $database) {
$this->pdo = new PDO( '...'); // Here is where you connect to the DB
}
public function query( $sql) {
return $this->pdo->query( $sql); // Or use prepared statments
}
}
Then you instantiate it outside of the class:
$db = new MySQLDB( 'user', 'pass', 'db');
And pass that $db object to one of your classes expecting an IDatabase:
$obj = new Test( $db); // Dependency Injection, woo hoo!
You can also look into having the MySQLDB class extending the PDO class, but that is your design choice.
Finally, you might be better off just sticking with PDO and getting rid of all this, as it is a great abstraction layer that works with many different databases.
So recently I've really started to use php actively, and I need some insights on different ways to use database connections.
At first I just used the simple mysql_connect():
<?php
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_DB, $connection);
?>
After a while I created a database class which I started to include and initialize in every file - something like this:
<?php
class MySQL_DB {
var $connection;
function MySQL_DB(){
$this->connection = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die(mysql_error());
mysql_select_db(DB_DB, $this->connection);
}
function query($q){
$res = mysql_query($q, $this->connection) or die(mysql_error());
return $res;
}
}
$database = New MySQL_DB;
?>
And this is what I'm using at the time - and it's working fine - but there are always ways to improve.
So my question to you is how do you manage your database connections?
Do you use classes?
What does your classes contain (just
the connection or even functions?)
What practices do you recommend?
I recommend to use PDO. Don't reinvent the weel. It's a nice OO-interface to many database engines.
Additionally I create a small function which just inititializes PDO object. So all connection settings can be changed in one place.
Your current approach is pretty standard, and works well. I used it for a long time. It's true that modules like PDO provide base functionality like this now, which is very nice as well and can get you away from problems with home-brew code.
However, I've taken the connection management one step further. If you get into a complex application, you might get into a situation where you have multiple databases, or heavy database use. Including a single database connection file and having a global $database variable becomes unwieldy for multiple databases, and it's unnecessary for application requests that might not need a database connection. Remember, connecting to the database is expensive.
What I've done is create a singleton DatabaseManager class that handles the database object for me, and makes sure multiple connections to a given DB don't get instantiated. Instead of initializing a new database object at the top of your app, you simply call on the DatabaseManager every time you need the object.
$db = DatabaseManager::getDatabase();
Here's an example class that I had whipped up for a CodeIgniter project. You can see in the getDatabase() function it simply loads CodeIgniter's default database object, which you would substitute for your own class (and run the connection routine for it) if you weren't using CI. This is a pretty simplistic management class, and could be extended to manage multiple connections to different databases fairly easily.
<?php
/**
* Implements the Singleton pattern to prevent multiple instantiations and connections
* to the application database.
*
*/
class Database_manager
{
private static $instance;
public $db;
/**
* Constructor function is declared private to prevent instantiation.
*
*/
protected function __construct()
{
parent::__construct();
}
/**
* Returns an instance of a Database_manager.
*
* #return object Database_manager object
*/
public static function getInstance()
{
if (self::$instance == null) {
$className = __CLASS__;
self::$instance = new $className();
}
return self::$instance;
}
public static function getDatabase()
{
$instance = self::getInstance();
if ($instance->db == null) {
//utilize CodeIgniter's database loader
$instance->db = $instance->load->database('',true);
if (! is_object($instance->db)) throw new Exception("Could not load database.");
}
return $instance->db;
}
}
Perhaps the most common advantage I get out of using this style of connection management is when I have to take down an application for database maintenance. By not instantiating a database connection until I need it, I can easily put up a "maintenance in progress" message on a site (short circuiting normal MVC dispatching), and not worry about requests to the application opening a DB connection while maintenance is in progress.
Usage of classes are the way to go to increase customized re-usability.
Bring in all generic implementations into the class. You are on the right track.
This website has the following clean approach.
This website link is no longer present. Archive Link.
class connection {
// Possible Modules are as follows:
// DBX_MYSQL, DBX_ODBC, DBX_PGSQL, DBX_MSSQL, DBX_FBSQL, DBX_SYBASECT, DBX_OCI8, DBX_SQLITE
private $module = DBX_MYSQL;
private $host = "localhost";
private $database = "test";
private $username = "testuser";
private $password = "testpass";
private $link;
private $result;
public $sql;
function __construct($database=""){
if (!empty($database)){ $this->database = $database; }
$this->link = dbx_connect($this->module,$this->host,$this->database,$this->username,$this->password);
return $this->link; // returns false if connection could not be made.
}
function query($sql){
if (!empty($sql)){
$this->sql = $sql;
$this->result = dbx_query($this->link,$sql,DBX_RESULT_UNBUFFERED);
return $this->result;
}else{
return false;
}
}
function fetch($result=""){
if (empty($result)){ $result = $this->result; }
return dbx_fetch_row($result);
}
function __destruct(){
dbx_close($this->link);
}
}
In your database manager example, you did not define a parent for your class.
Therefore, invoking parent::__constructor() yields an exception,
and also, you cannot use the load property of code ignitor.
Which class did you use as an extension for your DatabaseManager?
Since i do not know where you placed your databasemanager code, nor which class you used as its parent, i circumvented the exceptions by making the getDatabase() method receive an input parameter which i called $loader.
Normally, this $loader object will be the model class requiring access to a database.
public static function getDatabase($loader)
{
$instance = self::getInstance();
if ($instance->db == null) {
//utilize CodeIgniter's database loader
$instance->db = $loader->load->database('default',true);
if (! is_object($instance->db)) throw new Exception("Could not load database.");
}
return $instance->db;
}
Best regards.