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条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向