How do you manage database connections in php?

connection-pooling, database-connection, oop, php

Solution

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);
    }
}

Problem

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?

Original source