问题
I am thinking to connect to 2 database in my project in php.
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.
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??
回答1:
Short answer: Yes.
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)
Please look into the PHP Manual on PDO and connection management
Example:
$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);
}
Example without 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);
}
As you see above, the code for the two database drivers differs in its syntax - that is why i suggest to use 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.
回答2:
if you're using PDO, for example, thats possible. just create one pdo-object for each connection - just use the mysql-driver for mysql and an odbc-connection for access.
来源:https://stackoverflow.com/questions/10292789/connect-to-two-different-databases-in-php