Reusing an existing database connection with MDB2

January 4th, 2007. Tagged: mdb2, mysql, PEAR

This is a follow up to a question posted by Sam in my DB-2-MDB2 post. The question was if you can reuse an exisitng database connection you've already established and not have MDB2 creating a second connection.

When using a non-persistent connection

No worries in this case. No new connection will be established. As the PHP manual states:

If a second call is made to mysql_connect() with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned.

That is, if you don't set the fourth parameter to mysql_connect() to true. This parameter forces a new connection. BTW, in MDB2 if you do want to force a new connection, you have to set new_link in the DSN string to true

Bottom line, if you don't do anything special, the existing connection will be reused by MDB2. You can always verify that this is the case by calling phpinfo(INFO_MODULES); and looking in the "mysql" section.

When using a persistent connection

When using a persistent connection you have to do some additional steps to ensure that the same persistent connection is used by MDB2.

  • Tell MDB2 that you want a persistent connection - $mdb2->setOption('persistent', true);
  • Tell MDB2 which connection you want to use - $mdb2->connection = $link;, where $link is your existing connection
  • Set $mdb2->opened_persistent = true;

Here's an example:

// somewhere you've established a connection
$link = mysql_pconnect('localhost', 'root', '');
mysql_select_db('test', $link);
echo $link; // e.g. Resource id #5
// Create MDB2 object
require_once 'MDB2.php';
$dsn = 'mysql://root@localhost/test';
$mdb2 =& MDB2::factory($dsn);
// reuse your connection
$mdb2->setOption('persistent', true);
$mdb2->opened_persistent = true;
$mdb2->connection = $link;
// connect
echo $mdb2->connection; // Resource id #5
// check the "mysql" part to be sure

Tell your friends about this post: Facebook, Twitter, Google+

3 Responses

  1. Manually assigning a connection is not exactly support at this point. MDB2 actually does a few things during the connection procedure that are necessary. Depending on your settings it may make changes to the connection session or read some information from the database to determine how and if to emulate certain behaviors. With a bit of refactoring it might be possible to provide a way to provide a connection resource to MDB2 to use instead of creating a new one. File a feature request if you run into problems with the proposed solution.

  2. Stoyan Stefanov’s Blog: Reusing an existing database connection with MDB2…

  3. Thanks for that, I am now using the non-persistent connection solution. I had to alter the pre-existing connection call to use the same string as MDB2 but it works well. For your information, pg_connect() also reuses an existing connection if the connection string is exactly the same.

Leave a Reply