Connect to two different databases in PHP?

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

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

Using MS access is just getting data from it and MYSQL will be used to retrieve and store data.

Can I connect to the database at the same time?

+2


source to share


2 answers


Short answer: Yes .

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

Please see PHP Guide to 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 can see above, the code for the two database drivers is different in its syntax - which is why I suggest using PDO.

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

+5


source


if you are using PDO for example this is possible. just create one pdo object per connection - just use mysql driver for mysql and odbc-connection to access .



+2


source







All Articles