PHP同时连接多个mysql数据库的具体实现

方法一:

 1 <?php
 2 $conn1 = mysql_connect("127.0.0.1", "root","root","db1");
 3 mysql_select_db("Muma", $conn1);
 4 $conn2 = mysql_connect("127.0.0.1", "root","root","db2");
 5 mysql_select_db("product", $conn2);
 6  
 7 $sql = "select * from ip";
 8 $query = mysql_query($sql,$conn1); //添加连接$conn1
 9 if($row = mysql_fetch_array($query))
10 echo $row[0]."
";
11  
12 $sql = "select * from web ";
13 $query = mysql_query($sql, $conn2);
14 if($row = mysql_fetch_array($query))
15 echo $row[0];
16 ?>

方法2:在sql语句中关联所用数据库,此时可以省略mysql_query的第二个参数,即:

 1 <?php
 2 $conn1 = mysql_connect("127.0.0.1", "root","root","db1");
 3 mysql_select_db("db1", $conn1);
 4 $conn2 = mysql_connect("127.0.0.1", "root","root","db2");
 5 mysql_select_db("db2", $conn2);
 6  
 7 $sql = "select * from db1.ip"; //关联数据库
 8 $query = mysql_query($sql);
 9 if($row = mysql_fetch_array($query))
10 echo $row[0]."
";
11  
12 $sql = "select * from db2.web ";
13 $query = mysql_query($sql);
14 if($row = mysql_fetch_array($query))
15 echo $row[0];
16 ?>