Instance:
Copy Code code as follows:
<?php
$conn 1 = mysql_connect ("127.0.0.1", "root", "root", "db1");
mysql_select_db ("DB1", $conn 1);
$conn 2 = mysql_connect ("127.0.0.1", "root", "root", "DB2");
mysql_select_db ("DB2", $conn 2);
$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];
?>
There is a problem with this code, and an error occurs when the program executes: PHP Warning:mysql_fetch_array () expects parameter 1 to IS resource, boolean given in ....
Reason Analysis:
The program began to establish two database links, function mysql_query () prototype:
Resource mysql_query (String $query [, Resource $link _identifier])
Sends a query to the currently active database in the server associated with the specified connection identifier. If Link_identifier is not specified, the previous open connection is used. If there is no open connection, this function attempts to call the mysql_connect () function without arguments to establish a connection and use it. The query results are cached.
In this case, because Link_identifier is not specified, the first SQL is used by default, which is the last open link, $conn2, where the first SQL statement should actually use $CONN1, causing an error. So in order to be able to link multiple MySQL databases, you can use the following methods:
Method 1: Specify the connection used in the Mysql_query function, namely:
Copy Code code as follows:
<?php
$conn 1 = mysql_connect ("127.0.0.1", "root", "root", "db1");
mysql_select_db ("Muma", $conn 1);
$conn 2 = mysql_connect ("127.0.0.1", "root", "root", "DB2");
mysql_select_db ("Product", $conn 2);
$sql = "SELECT * from IP";
$query = mysql_query ($sql, $conn 1); Add Connection $conn1
if ($row = mysql_fetch_array ($query))
echo $row [0]. " \ n ";
$sql = "SELECT * from Web";
$query = mysql_query ($sql, $conn 2);
if ($row = mysql_fetch_array ($query))
echo $row [0];
?>
Method 2: To associate the database used in the SQL statement, you can omit the second parameter of Mysql_query, which is:
Copy Code code as follows:
<?php
$conn 1 = mysql_connect ("127.0.0.1", "root", "root", "db1");
mysql_select_db ("DB1", $conn 1);
$conn 2 = mysql_connect ("127.0.0.1", "root", "root", "DB2");
mysql_select_db ("DB2", $conn 2);
$sql = "SELECT * from Db1.ip";//association database
$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];
?>