views:

301

answers:

3

Is it possible to keep all my database related configuration (hostnames, usernames, passwords, and databases) as well as the function to connect to and select the correct database in a seperate class?

I tried something like this:

class Database
{
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );
    function __construct() {
        $this->connect();
    }
    function connect() {
        $db = $this->config;
        $conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
        if(!$conn) {
            die("Cannot connect to database server"); 
        }
        if(!mysql_select_db($db['database'])) {
            die("Cannot select database");
        }
    }
}

And then in another class I would use in the classes __construct function:

require_once('database.php');
var $db_conn = new Database();

But this doesnt save the connection, it ends up defaulting to the servers local db connection. Or do I have to do the database commands everytime before I execute some database commands?

A: 

You can certainly keep your connection info in a separate file.

Just save your connection object - $conn in your connect() function - in a class variable. You'll then be able to reuse it across calls.

Alex
A: 

In your method connect() $conn is only a local variable that only exists in the scope of that method. As soon as the method returns there will be no (other) reference to the connection resource and it will be collected/disposed. You'll need at least

$this->conn = mysql_connect(...)
VolkerK
I just tried adding this to the Database class: var $conn;and to the connect() method in the Database class: $this->conn = mysql($db['hostname'], $db['username'], $db['password']);In the __contruct of the other class I have a class variable $db that is filled with this in the __construct of that class: $this->db = new Database();I am still getting this error when trying to make a query: Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
trobrock
I have posted the entire Database class I am using as well as some testing files at: http://gist.github.com/158389 If anyone could take a look and see if they can find the problem.
trobrock
+3  A: 

I modified your class to work as you seem to be expecting it to:

<?php
class Database
{
    var $conn = null;
    var $config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    function __construct() {
        $this->connect();
    }

    function connect() {
        if (is_null($this->conn)) {
            $db = $this->config;
            $this->conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->conn;
    }
}

Usage:

$db = new Database();
$conn = $db->connect();

Note that you can call connect() as many times as you like and it will use the current connection, or create one if it doesn't exist. This is a good thing.

Also, note that each time you instantiate a Database object (using new) you will be creating a new connection to the database. I suggest you look into implementing your Database class as a Singleton or storing it in a Registry for global access.

You can also do it the dirty way and shove it in $GLOBALS.

Edit

I took the liberty of modifying your class to implement the Singleton pattern, and follow the PHP5 OOP conventions.

<?php
class Database
{
    protected static $_instance = null;

    protected $_conn = null;

    protected $_config = array(
        'username' => 'someuser',
        'password' => 'somepassword',
        'hostname' => 'some_remote_host',
        'database' => 'a_database'
    );

    protected function __construct() {
    }

    public static function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getConnection() {
        if (is_null($this->_conn)) {
            $db = $this->_config;
            $this->_conn = mysql_connect($db['hostname'], $db['username'], $db['password']);
            if(!$this->_conn) {
                die("Cannot connect to database server"); 
            }
            if(!mysql_select_db($db['database'])) {
                die("Cannot select database");
            }
        }
        return $this->_conn;
    }

    public function query($query) {
        $conn = $this->getConnection();
        return mysql_query($query, $conn);
    }
}

Usage:

$res = Database::getInstance()->query("SELECT * FROM foo;");

or

$db = Database::getInstance();
$db->query("UPDATE foo");
$db->query("DELETE FROM foo");
hobodave