如何在两个服务器中连接两个mysql数据库

时间:2017-04-25 09:57:25

标签: php mysql

我想连接两个mysql数据库,一个位于localhost,另一个位于服务器

这是我到目前为止所做的,我没有得到任何错误或数据

<?php
$con=mysql_connect('120.247.201.8:3306','root','root');
$con1=mysql_connect('localhost','root','');

//mysql_connect('localhost','root','');
if(!$con){
    die('Try Again');
}


if(!$con1){
    die('Try Again');
}

    mysql_select_db("iot",$con1); 
mysql_select_db("lora_gateway",$con);
$result =mysql_query("SELECT lora_gateway.`server_log`.`created_at`, lora_gateway.`server_log`.`temperature`FROM iot.`device` inner JOIN  `lora_gateway`.`server_log` on `lora_gateway`.`server_log`.`gateway_Id` = `iot`.`device`.`gatewayId` where iot.`device`.`deviceId`='23' ORDER BY lora_gateway.`server_log`.`created_at` desc");

$num= mysql_num_rows($result);



print_r($num);
?>

3 个答案:

答案 0 :(得分:1)

首先,尝试使用PDO或至少使用mysqli_函数。这是未来。 :)

mysql_query的第二个参数,即连接链接,是可选的。如果省略,则使用与mysql_connect打开的最后一个连接。 (见php.net Documentation

Ergo,始终使用$con$con1作为第二个参数,以便使用正确的连接。

然后,如果您的查询正确,它应该按预期工作。

答案 1 :(得分:1)

这是多个服务器,连接和数据库的解决方案。

  • 两个或更多MySQL 5 db服务器
  • 两个或更多地点(本地和/或其他任何地方)
  • 两个或更多不同的数据库
  • 两个或多个表格和字段

经过测试和工作正常: - )

//Define your database connections and select your database want to use. In this example I use two connections and two DBs. But you can use more than two.

<?php
    //MySQL Server 1
    $dbhost1 = "127.0.0.1";
    $dbuser1 = "dbuser1";
    $dbpassword1 = "dbpass1";
    $db1 = "database1";
    $connection1 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
    mysql_select_db($db1,$connection1);

    //MySQL Server 2
    $dbhost2 = "xxx.xxx.xxx.xxx";
    $dbuser2 = "dbuser2";
    $dbpassword2 = "dbpass2";
    $db2 = "database2";
    $connection2 = mysql_connect($dbhost1,$dbuser1,$dbpassword1) or die (mysql_error());
    mysql_select_db($db2,$connection2);    

    //The SQL statement
    $sql =" SELECT database1.tablename1.fieldname1 AS field1, database2.tablename2.fieldname2 AS field2 FROM database1.tablename1,database2.tablename2";

    //Execute query and collect results in $results
    $results = mysql_query($sql);

    //Print result until end of records
    while($rows = mysql_fetch_array($results)){
        print $rows["field1"]." | ".$rows["field2"]."<br>";
    }

    ?>

答案 2 :(得分:0)

如何添加与mysql_query()的连接?

$result = mysql_query("SELECT lora_gateway.`server_log`.... desc", $con);