douping3427 2014-12-16 07:13
浏览 32
已采纳

如何连接到同一个类中的两个不同的MySQL DB

I have this class called dataBase . Looks like this

    class dataBase
    {

        private $conexion;
        private $paisConexion;
        var $db;
        function __construct($db='default')
        {
            $this->db = $db;
            include '../settings/variables.php';

            if(isset($bbdd)){

            $conexion = mysql_connect($bbdd["server"], $pais[0]['user'], $pais[0]['pass']) or die('No se pudo conectar: '.mysql_error());
            // Seleccionamos la base de datos
            mysql_select_db($x[0]['database']) or die('No se pudo seleccionar la base de datos');

            if($conexion)
            {   
            $paisConexion = mysql_connect($bbdd["server"], $pais[$this->db]['user'], $pais[$this->db]['pass']) or die('No se pudo conectar: '.mysql_error());

            mysql_select_db($pais[$this->db]['database']) or die('No se pudo seleccionar la base de datos');

            }


            }
            else{
                echo 'El sistema no se pudo conectar a la base de datos.';
                exit;
            }
        }

public function execute($sql)
    {
        $result = mysql_query($sql) or die("ERROR: Ejecuci&oacute;n de consulta: $sql<br>
");
        return $result;
    }
}

I am trying to make two connection to two different database using the variable $conexion and $paisConexion .

My question is is it possible to do something like this .

I mean suppose I am creating an object for the class like this

$obj = new dataBase(1); $res = obj->execute($sql);

So how the the class will decide which of the connection it has to use ? .

I think I am doing this wrong way . If any one has any idea please let me know

Thanks in Advance

  • 写回答

3条回答 默认 最新

  • doumao1047 2014-12-16 07:44
    关注

    You can't create one class for both databases. Unless you pass some parameter that specifies witch connection to use. Also than you must use two different variables for different connections. And don't use deprecated mysql_* functions

    class DataBase {
        // only private variables accessed by functions
        private $localDb, $remoteDb;
        // Always use constants instead of magic numbers
        const LOCAL = 1, REMOTE = 2
    
        public function _construct() {
            $this->localDb= new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
            $this->remoteDb= new PDO('mysql:host=remore;dbname=test2', 'username', 'password');
        }
    
        // Can't use constants in function header           - - - - -v
        public function execute($queryString, $params = [], $useDb = 1) {
            // static:: will take variable from this class and not from parent class (if extends something)
            if ($useDb == static::LOCAL) {
                $db = $this->local;
            } elseif ($useDb == static::REMOTE) {
                $db = $this->remote;
            }
    
            $query = $db->prepare($queryString);
    
            // Usage of prepared statement
            return $query->execute($params);
        }
    }
    
    $db = new DataBase();
    $db->execute(
        'SELECT * FROM table WHERE column = :columnVal', // named placeholders instead of tons of '?' 
        [':columnVal' => 5], // some parameters
        DataBase::LOCAL // Constant from class
    );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算