连接到PHP中的两个不同的数据库? [英] Connect to two different databases in PHP?

查看:185
本文介绍了连接到PHP中的两个不同的数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用php连接到我的项目中的2个数据库.

I am thinking to connect to 2 database in my project in php.

一个是我们的票务系统中使用MS ACESS的现有数据库,另一个是使用我的MYSQL的即时消息.

one is an existing database from our ticketing system that uses MS ACESS and the other one is the one im using now its MYSQL.

使用MS访问只是从中检索数据,而MYSQL将用于检索和存储数据.

The use of the MS access is just to retrieve data from it and the MYSQL will be used to both retrieve and store data.

是否可以同时连接到两个数据库?

Is it possible to connect to both database at the same time??

推荐答案

简短答案:.

长答案:
您应该确保您的代码始终使用连接标识符以避免混淆,并拥有清晰易读的代码. (尤其是当您使用ODBC或PDO等抽象层连接到两个数据库时)

Long answer:
You should ensure that your code always uses connection identifiers to avoid confusion and have clean, readable code. (Especially when you connect to both databases using an abstraction layer like ODBC or PDO)

请查看有关PDO和连接管理的PHP手册

示例:

$link_mysql = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$link_msaccess = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\test.mdb");

// query MySQL DB
foreach($link_mysql->query('SELECT * FROM test') as $row) {
    print_r($row);
}

// query MS Access DB
foreach($link_msaccess->query('SELECT * FROM omg_its_access') as $row) {
    print_r($row);
}

没有PDO的示例:

$link_mysql = mysql_connect("localhost", $user, $pass);
mysql_select_db("test", $link_mysql);

$link_msaccess = odbc_connect("odbc:Driver={Microsoft Access Driver (*.mdb)};Dbq=C:\\test.mdb");

// you may omit the link identifier for MySQL, but i suggest to use it explicitly 
$res1 = mysql_query('SELECT * FROM test', $link_mysql);
while ($row = mysql_fetch_row($res1)) {
    print_r($row);
}
// for ODBC the link identifier is mandatory
$res2 = odbc_exec($link_msaccess, 'SELECT * FROM omg_its_access');
while ($row = odbc_fetch_row($res2)) {
    print_r($row);
}

如上所述,这两个数据库驱动程序的代码在语法上有所不同-这就是为什么我建议使用PDO的原因.

PDO将避免很多麻烦,并且如果您以后决定切换到另一个数据库驱动程序,则将变得更加容易.它抽象了所有数据库驱动程序,并为您提供了一个简单的界面,以相同的语法处理所有数据库驱动程序.

PDO will avoid a lot of hassle and will make switching to another database driver much easier if you decide to do so later. It abstracts all database drivers and gives you a simple interface to handle them all with the same syntax.

这篇关于连接到PHP中的两个不同的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆