如何在一个网页上连接多个 MySQL 数据库?
我的信息分布在几个数据库中,我想使用 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 起移除(请参阅 http://php.net/manual/intro.mysql.php),使用 mysqli_xx
函数或从@Troelskn 中查看下面的答案
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 用户可以访问两个数据库并且它们在同一台主机上(即两个数据库都可以从同一个连接访问),您可以:
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.