$servername1 = "localhost1";
$username1 = "user1";
$password1 = "pwd";
$dbname1 = "dbs1";
$servername2 = "localhost2";
$username2 = "user2";
$password2 = "ped2";
$dbname2 = "dbs2";
// Create connection
$conn = new mysqli($servername1, $username1, $password1, $dbname1);
// Check connection
if ($conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2, $dbname2);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
}
可以实现这种类型的连接吗?当我故意在第一个数据库凭据中实现此错误时,我收到一条警告未知MySQL服务器主机' localhost1' 并且不会加载页面。为什么这不起作用?
答案 0 :(得分:0)
您应该使用“localhost”或IP地址连接到SQL Server。在您的情况下,它尝试连接到不存在的“localhost1”(如在您的变量中)(除非您更改了主机文件)。尝试使用IP(127.0.0.1用于localhost,其他任何用于备份)
干杯, JCK
答案 1 :(得分:0)
您可以先尝试Ping。
OR
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")
" . $mysqli->connect_error;
}
OR
extension_loaded("mysql");
答案 2 :(得分:0)
我创建了一个数据库列表,然后遍历它们并尝试连接。使用多个数据库应该没问题。无法使用localhost1和localhost2(只有localhost可能是127.0.0.1)。你应该使用IP地址。
以下是代码:
<?php
$Databases = array(
0 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database1',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_3,
),
1 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database2',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_2,
),
2 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database3',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_1,
),
);
for($i=0;$i<count($Databases);$i++)
{
if($last_db_ind>=count($Databases)){
$last_db_ind=0;
}
if(($db =& db_connect($last_db_ind++))==false){
echo 'Connection failed for DB: '. $Databases["db_name"] . ', DB index: '.$last_db_ind;
continue;
}
?>