Home >php教程 >php手册 >PHP同时连接多个mysql数据库示例代码

PHP同时连接多个mysql数据库示例代码

WBOY
WBOYOriginal
2016-06-13 09:40:361204browse

实例:

复制代码 代码如下:


$conn1 = mysql_connect("127.0.0.1", "root","root","db1");
mysql_select_db("db1", $conn1);
$conn2 = mysql_connect("127.0.0.1", "root","root","db2");
mysql_select_db("db2", $conn2);

$sql = "select * from ip";
$query = mysql_query($sql);
if($row = mysql_fetch_array($query))
echo $row[0]."\n";

$sql = "select * from web ";
$query = mysql_query($sql);
if($row = mysql_fetch_array($query))
echo $row[0];
?>


这段代码存在问题,在程序执行时会报错:PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in ....

原因分析:

程序开始建立两个数据库链接,函数mysql_query()原型:

resource mysql_query ( string $query [, resource $link_identifier ] )

向与指定的连接标识符关联的服务器中的当前活动数据库发送一条查询。如果没有指定 link_identifier,则使用上一个打开的连接。如果没有打开的连接,本函数会尝试无参数调用 mysql_connect() 函数来建立一个连接并使用之。查询结果会被缓存。

在本例中由于没有指定link_identifier,所以,在执行第一条sql时,默认使用的是上一个打开的链接,即$conn2,而实际上第一条sql语句应该使用的是$conn1,所以导致报错,所以为了能够链接多个mysql数据库,可以使用如下方法:

方法1:在mysql_query函数中指定所用连接,即:

复制代码 代码如下:


$conn1 = mysql_connect("127.0.0.1", "root","root","db1");
mysql_select_db("Muma", $conn1);
$conn2 = mysql_connect("127.0.0.1", "root","root","db2");
mysql_select_db("product", $conn2);

$sql = "select * from ip";
$query = mysql_query($sql,$conn1); //添加连接$conn1
if($row = mysql_fetch_array($query))
echo $row[0]."\n";

$sql = "select * from web ";
$query = mysql_query($sql, $conn2);
if($row = mysql_fetch_array($query))
echo $row[0];
?>


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

复制代码 代码如下:


$conn1 = mysql_connect("127.0.0.1", "root","root","db1");
mysql_select_db("db1", $conn1);
$conn2 = mysql_connect("127.0.0.1", "root","root","db2");
mysql_select_db("db2", $conn2);

$sql = "select * from db1.ip"; //关联数据库
$query = mysql_query($sql);
if($row = mysql_fetch_array($query))
echo $row[0]."\n";

$sql = "select * from db2.web ";
$query = mysql_query($sql);
if($row = mysql_fetch_array($query))
echo $row[0];
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn