duandui2803 2013-05-14 07:28
浏览 58

使用多通道或任何设计模式的多个数据库连接

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

}
?>
  • 写回答

1条回答 默认 最新

  • douzoudang1511 2013-05-14 07:45
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?