PHP - 多个MySQL连接

时间:2016-09-01 04:27:07

标签: php mysql mysqli

好的,这是我的连接代码:

$servername = "host";
$username = "user";
$password = "pass";
$db1 = "db1";
$db2 = "db2";
// Create connection
$conn = new mysqli($servername, $username, $password, $db1); // $db1 is here as the default, is this ok?
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

然后我使用此连接运行一个函数,它适用于$db1

$sql = "SELECT etc etc;                 
$result = $conn->query($sql); 

等等

问题是当我尝试将数据库更改为$db2时,我使用它:

$conn->select_db($db2);

现在它只返回第二个数据库($db2)的值,而$db1中的那个不再显示在页面上,它没有显示任何值

感谢阅读。

3 个答案:

答案 0 :(得分:1)

连接不同数据库时使用了两种不同的连接:

数据库一连接:

$conn = new mysqli($servername, $username, $password, $db1);
$sql = "SELECT etc etc;
$result = $conn->query($sql);

数据库二连接:

$conn1 = new mysqli($servername, $username, $password, $db2);
$sql = "SELECT etc etc;
$result = $conn1->query($sql);

问题是您已经将conn分配给了DB1,因此如果您通过选择DB2运行它将显示错误或者不会产生任何结果。因此,在选择多数据库时,您可以使用不同的连接变量

答案 1 :(得分:0)

  

$ db1中的那个不再出现在页面上,它没有显示任何值。

如何让它$conn->select_db($db1);回来?

答案 2 :(得分:0)

创建两个配置文件

<强> db1.php

$servername = "host1";
$username = "user1";
$password = "pass1";
$db = "db1";

<强> db2.php

$servername = "host2";
$username = "user2";
$password = "pass2";
$db = "db2";


//connection to db1
include("db1.php");
$conn = new mysqli($servername, $username, $password, $db); 
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//db1 codes

--------------------
//connection to db2
include("db2.php");
$conn = new mysqli($servername, $username, $password, $db); 
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//db2 codes