如何在单个网页上连接到多个MySQL数据库? [英] How do you connect to multiple MySQL databases on a single webpage?
问题描述
我的信息分布在几个数据库中,我想使用PHP将所有信息放到一个网页上.我想知道如何在一个PHP网页上连接到多个数据库.
I have information spread out across a few databases and want to put all the information onto one webpage using PHP. I was wondering how I can connect to multiple databases on a single PHP webpage.
我知道如何使用以下方法连接到单个数据库:
I know how to connect to a single database using:
$dbh = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
但是,我可以使用多个"mysql_connect"命令打开其他数据库吗,如果我连接了多个数据库,PHP如何知道我要从哪个数据库中提取信息.
However, can I just use multiple "mysql_connect" commands to open the other databases, and how would PHP know what database I want the information pulled from if I do have multiple databases connected.
推荐答案
警告: mysql_xx
自php 5.5起已弃用,自php 7.0起已删除(请参见
Warning : mysql_xx
functions are deprecated since php 5.5 and removed since php 7.0 (see http://php.net/manual/intro.mysql.php), use mysqli_xx
functions or see the answer below from @Troelskn
您可以多次调用mysql_connect()
,但是如果参数相同,则需要为'$new_link
'(第四个)参数传递true,否则将重用相同的连接.例如:
You can make multiple calls to mysql_connect()
, but if the parameters are the same you need to pass true for the '$new_link
' (fourth) parameter, otherwise the same connection is reused. For example:
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
然后查询数据库1传递第一个链接标识符:
Then to query database 1 pass the first link identifier:
mysql_query('select * from tablename', $dbh1);
对于数据库2,通过第二个:
and for database 2 pass the second:
mysql_query('select * from tablename', $dbh2);
如果不传递链接标识符,则使用最后创建的连接(在这种情况下,该连接由$dbh2
表示),例如:
If you do not pass a link identifier then the last connection created is used (in this case the one represented by $dbh2
) e.g.:
mysql_query('select * from tablename');
其他选项
如果MySQL用户可以访问两个数据库,并且它们位于同一主机上(即,两个DB可以从同一连接访问),则可以:
If the MySQL user has access to both databases and they are on the same host (i.e. both DBs are accessible from the same connection) you could:
- 保持一个连接打开,并在必要时调用
mysql_select_db()
进行交换.我不确定这是否是干净的解决方案,您最终可能会查询错误的数据库. - 在查询中引用表时指定数据库名称(例如
SELECT * FROM database2.tablename
).实施起来可能很痛苦.
- Keep one connection open and call
mysql_select_db()
to swap between as necessary. I am not sure this is a clean solution and you could end up querying the wrong database. - Specify the database name when you reference tables within your queries (e.g.
SELECT * FROM database2.tablename
). This is likely to be a pain to implement.
还请阅读troelskn的答案,因为如果您能够使用PDO而不是较早的扩展名,那是一种更好的方法.
Also please read troelskn's answer because that is a better approach if you are able to use PDO rather than the older extensions.
这篇关于如何在单个网页上连接到多个MySQL数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!