Instance:
Copy codeThe Code is as follows:
<? Php
$ 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];
?>
There is a problem with this Code. During program execution, the following error occurs: PHP Warning: mysql_fetch_array () expects parameter 1 to be resource, boolean given in ....
Cause analysis:
The program starts to establish two database links. The prototype of the function mysql_query () is as follows:
Resource mysql_query (string $ query [, resource $ link_identifier])
Sends a query to the active database on the server associated with the specified connection identifier. If link_identifier is not specified, the last opened connection is used. If no connection is enabled, this function will try to call the mysql_connect () function without parameters to establish a connection and use it. The query results are cached.
In this example, because link_identifier is not specified, the last opened link, namely $ conn2, is used by default when the first SQL statement is executed, in fact, the first SQL statement should use $ conn1, which leads to an error. To connect to multiple mysql databases, you can use the following method:
Method 1: Specify the connection used in the mysql_query function, namely:
Copy codeThe Code is as follows:
<? Php
$ 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); // Add a connection $ 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];
?>
Method 2: link the database used in the SQL statement. In this case, the second parameter of mysql_query can be omitted, namely:
Copy codeThe Code is as follows:
<? Php
$ 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"; // associate a 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];
?>