user2380555
user2380555

Reputation: 13

Multiple database connections using multiton or any design pattern

I have following code for multiple database connections. It's not good design. Everything is static. But don't know how to improve it. i can add more functions like prepare query, but presently I want good/clean design. I tried to make multiton design pattern. The requirements is like, first I will connect with 1 database, then get database details of all other mysql clients, then loop and connect with each database and do something. So, I need multiple connections.

<?php

class db_class{

private static $instance = array();

private function __construct(){ }

public static function get_instance($type , $db_detail_array=array()){
    $host = $db_detail_array['host'];
    $username = $db_detail_array['username'];
    $database = $db_detail_array['database'];
    $password = $db_detail_array['password'];
    if(empty($host) or empty($username) or empty($database) or empty($password)){
        return;
    }

    if(empty(self::$instance[$type])) {
            self::$instance[$type] = new mysqli($host, $username, $password, $database);
        if (@self::$instance[$type]->connect_errno) {
            echo self::$last_err = "Connect failed";
        }
        }
}

static function fetch_assoc($query,$type){
    $db_query = self::run_query($query,$type);
    $rows = array();
    while($row = @$db_query->fetch_assoc()){
        $rows[] = $row;
    }
    $db_query->free();
    return($rows);
}

static function escape($type,$value){
    $value = self::$instance[$type]->real_escape_string($value);
    return($value);
}

static function run_query($query,$type){
    self::$instance[$type]->ping();
    $db_query = self::$instance[$type]->query($query);
    if(self::$instance[$type]->error){
        echo self::$last_err = self::$instance[$type]->error;echo "<p>$query, $type</p>";
        return;
    }
    return($db_query) ;
}

static function num_rows($query,$type){
    $db_query = self::run_query($query,$type);
    $num_rows = $db_query->num_rows;
    return($num_rows);
}

static function disconnect($type){
    @self::$db_obj[$type]->close();
}

}
?>

Upvotes: 0

Views: 894

Answers (1)

Volkan
Volkan

Reputation: 2210

Please have a look at PDO.

It is an unifier database object exposing a common and effective interface.

It supports server types other than mysql too.

Even using it plainly will be satisfactory.

Upvotes: 1

Related Questions