简体   繁体   English

如何在单个网页上连接到多个MySQL数据库?

[英]How do you connect to multiple MySQL databases on a single webpage?

I have information spread out across a few databases and want to put all the information onto one webpage using PHP. 我的信息分布在几个数据库中,并希望使用PHP将所有信息放到一个网页上。 I was wondering how I can connect to multiple databases on a single PHP webpage. 我想知道如何在单个PHP网页上连接到多个数据库。

I know how to connect to a single database using: 我知道如何使用以下方法连接到单个数据库:

$dbh = mysql_connect($hostname, $username, $password) 
        or die("Unable to connect to MySQL");

However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected. 但是,我可以仅使用多个“ mysql_connect”命令来打开其他数据库吗?如果我确实连接了多个数据库,PHP如何知道要从哪个数据库中提取信息?

Warning : mysql_xx functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php ), use mysqli_xx functions or see the answer below from @Troelskn 警告: mysql_xx因为PHP 5.5的功能已被取消,因为PHP 7.0(见删除http://php.net/manual/intro.mysql.php ),使用mysqli_xx功能或参阅下面的答案从@Troelskn


You can make multiple calls to mysql_connect() , but if the parameters are the same you need to pass true for the ' $new_link ' (fourth) parameter, otherwise the same connection is reused. 您可以多次调用mysql_connect() ,但是如果参数相同,则需要为' $new_link '(第四个)参数传递true,否则将重用相同的连接。 For example: 例如:

$dbh1 = mysql_connect($hostname, $username, $password); 
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

Then to query database 1 pass the first link identifier: 然后要查询数据库1,传递第一个链接标识符:

mysql_query('select * from tablename', $dbh1);

and for database 2 pass the second: 对于数据库2,通过第二个:

mysql_query('select * from tablename', $dbh2);

If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2 ) eg: 如果未传递链接标识符,则使用最后创建的连接(在本例中为$dbh2表示的$dbh2 ),例如:

mysql_query('select * from tablename');

Other options 其他选择

If the MySQL user has access to both databases and they are on the same host (ie both DBs are accessible from the same connection) you could: 如果MySQL用户可以访问两个数据库,并且它们位于同一主机上(即,两个DB可以从同一连接访问),则可以:

  • Keep one connection open and call mysql_select_db() to swap between as necessary. 保持一个连接打开,并根据需要调用mysql_select_db()进行交换。 I am not sure this is a clean solution and you could end up querying the wrong database. 我不确定这是否是干净的解决方案,您最终可能会查询错误的数据库。
  • Specify the database name when you reference tables within your queries (eg SELECT * FROM database2.tablename ). 在查询中引用表时,请指定数据库名称(例如SELECT * FROM database2.tablename )。 This is likely to be a pain to implement. 实施起来可能很痛苦。

Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions. 另外,请阅读troelskn的答案,因为如果您能够使用PDO而不是较旧的扩展名,那么这是一种更好的方法。

If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO , since this is slowly becoming the new standard. 如果使用PHP5(并且应该弃用PHP4),则应该使用PDO ,因为这正逐渐成为新的标准。 One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code. PDO的一个(非常)重要的好处是,它支持绑定的参数,这使代码更加安全。

You would connect through PDO, like this: 您将通过PDO进行连接,如下所示:

try {
  $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

(Of course replace databasename, username and password above) (当然,请替换上面的数据库名称,用户名和密码)

You can then query the database like this: 然后,您可以像这样查询数据库:

$result = $db->query("select * from tablename");
foreach ($result as $row) {
  echo $row['foo'] . "\n";
}

Or, if you have variables: 或者,如果您有变量:

$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();

If you need multiple connections open at once, you can simply create multiple instances of PDO: 如果您需要一次打开多个连接,则可以简单地创建多个PDO实例:

try {
  $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username', 'password');
  $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username', 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

I just made my life simple: 我只是让我的生活变得简单:

CREATE VIEW another_table AS SELECT * FROM another_database.another_table;

hope it is helpful... cheers... 希望对您有帮助...干杯...

Instead of mysql_connect use mysqli_connect . 代替mysql_connect,使用mysqli_connect

mysqli is provide a functionality for connect multiple database at a time. mysqli提供了一次连接多个数据库的功能。

$Db1 = new mysqli($hostname,$username,$password,$db_name1); 
// this is connection 1 for DB 1

$Db2 = new mysqli($hostname,$username,$password,$db_name2); 
// this is connection 2 for DB 2

Try below code: 试试下面的代码:

    $conn = mysql_connect("hostname","username","password");
    mysql_select_db("db1",$conn);
    mysql_select_db("db2",$conn);

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below 您可以从两个数据库中获取上述查询的数据,如下所示

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;
}

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;
}

print_r($data1);
print_r($data2);

Unless you really need to have more than one instance of a PDO object in play, consider the following: 除非您确实需要一个以上的PDO对象实例,否则请考虑以下事项:

$con = new PDO('mysql:host=localhost', $username, $password, 
      array(PDO::ATTR_PERSISTENT => true));

Notice the absence of dbname= in the construction arguments. 请注意,构造参数中没有dbname=

When you connect to MySQL via a terminal or other tool, the database name is not needed off the bat. 通过终端或其他工具连接到MySQL时,不需要数据库名称。 You can switch between databases by using the USE dbname statement via the PDO::exec() method. 您可以通过PDO::exec()方法使用USE dbname语句在数据库之间切换。

$con->exec("USE someDatabase");
$con->exec("USE anotherDatabase");

Of course you may want to wrap this in a catch try statement. 当然,您可能希望将其包装在catch try语句中。

$dbh1 = mysql_connect($hostname, $username, $password);  
$dbh2 = mysql_connect($hostname, $username, $password, true); 

mysql_select_db('database1', $dbh1); 
mysql_select_db('database2',$dbh2); 

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);

This is the most obvious solution that I use but just remember, if the username / password for both the database is exactly same in the same host, this solution will always be using the first connection. 这是我使用的最明显的解决方案,但请记住,如果两个数据库的用户名/密码在同一主机中完全相同,则此解决方案将始终使用第一个连接。 So don't be confused that this is not working in such case. 因此,请勿混淆在这种情况下不起作用。 What you need to do is, create 2 different users for the 2 databases and it will work. 您需要做的是,为2个数据库创建2个不同的用户,然后它将起作用。

You might be able to use MySQLi syntax, which would allow you to handle it better. 您也许可以使用MySQLi语法,这将使您更好地处理它。

Define the database connections, then whenever you want to query one of the database, specify the right connection. 定义数据库连接,然后每当要查询数据库之一时,指定正确的连接。

Eg: 例如:

$Db1 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 1st database connection 
$Db2 = new mysqli('$DB_HOST','USERNAME','PASSWORD'); // 2nd database connection

Then to query them on the same page, use something like: 然后要在同一页面上查询它们,请使用类似以下内容:

$query = $Db1->query("select * from tablename")
$query2 = $Db2->query("select * from tablename")
die("$Db1->error");

Changing to MySQLi in this way will help you. 以这种方式更改为MySQLi将为您提供帮助。

You don't actually need select_db . 您实际上并不需要select_db You can send a query to two databases at the same time. 您可以同时将查询发送到两个数据库。 First, give a grant to DB1 to select from DB2 by GRANT select ON DB2.* TO DB1@localhost; 首先,通过GRANT select ON DB2.* TO DB1@localhost;授予DB1DB2 GRANT select ON DB2.* TO DB1@localhost; . Then, FLUSH PRIVILEGES; 然后, FLUSH PRIVILEGES; . Finally, you are able to do 'multiple-database query' like SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2 etc. (Don't forget that you need 'root' access to use grant command) 最后,您可以执行“多个数据库查询”,例如SELECT DB1.TABLE1.id, DB2.TABLE1.username FROM DB1,DB2等。(别忘了您需要使用root用户权限才能使用Grant命令)

if you are using mysqli and have two db_connection file. 如果您使用的是mysqli并具有两个db_connection文件。 like first one is 像第一个是

define('HOST','localhost');
define('USER','user');
define('PASS','passs');
define('**DB1**','database_name1');

$connMitra = new mysqli(HOST, USER, PASS, **DB1**);

second one is 第二个是

    define('HOST','localhost');
    define('USER','user');
    define('PASS','passs');
    define(**'DB2**','database_name1');

    $connMitra = new mysqli(HOST, USER, PASS, **DB2**);

SO just change the name of parameter pass in mysqli like DB1 and DB2. 因此,只需在mysqli中更改参数传递的名称,例如DB1和DB2。 if you pass same parameter in mysqli suppose DB1 in both file then second database will no connect any more. 如果您在mysqli中传递相同的参数,假设两个文件中都有DB1,则第二个数据库将不再连接。 So remember when you use two or more connection pass different parameter name in mysqli function 因此请记住,当您使用两个或多个连接时,请在mysqli函数中传递不同的参数名称

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

i had done this in laravel 我在拉拉维(Laravel)做过

 ini_set('max_execution_time', 3600);
                $old_users = DB::connection('mysql2')->table('user_master')->get();
                foreach ($old_users as $old_user) {
                    if ($old_user->usr_phone != "0") {
                        $password = base64_decode($old_user->usr_pwd);
                        $password = Hash::make($password);
                        if ($old_user->device_type == "1") {
                            $device_type = "ios";
                        } else if ($old_user->device_type == "2") {
                            $device_type = "android";
                        } else {
                            $device_type = "web";
                        }
                        $user = new User;
                        $user->name = $old_user->usr_name;
                        $user->email = $old_user->usr_email;
                        $user->points_exp_date = "2018-08-02";                        try {
                            $user->save();
                        } catch (\Exception $e) {
                            echo ("<script>console.log('duplicate entry in user: " . $user->name . "');</script>");
                        }
                        Log::info('user saved');
                    }
                }

And this is my sample code 这是我的示例代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM