Search code examples
phpmysqlsqldatabasemultiple-databases

Query two databases with the same query


I need to run the same query on two different databases.

I edited my previous db class obtaining this

class Db {

function connect() {
    $db = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Error");
    mysql_select_db(DB_NAME, $db);
    return $db;
}

function connect2() {
    $db = mysql_connect(DB_HOST2, DB_USER2, DB_PASSWORD2) or die("Error 2");
    mysql_select_db(DB_NAME2, $db);
    return $db;
}

function sql_query($sql) {

    $result = mysql_query($sql, $this->connect()) or die(mysql_error());
    $result2 = mysql_query($sql, $this->connect2()) or die(mysql_error());   



}  }

Is there a way to avoid the connection to the databases each time? I already tried using $GLOBALS to save the database links but it doesn't seem to work.

Thanks a lot


Solution

  • Take a look at the PHP PDO manual

    http://www.php.net//manual/en/book.pdo.php

    Using PDO you can make two connections at the same time then you can run two queries on two different databases too ;)