0

I've literally spent half a day trying to find a solution for this problem.

From one WordPress installation I need to query multiple other WordPress installations' databases.

I'd very much like to use the $wpdb way, as this is what I've always used (just haven't ever had the need to access more than one database).

I've created a wpdb object by using this method:

$new_db_connection = new wpdb(*DB INFORMATION INSERTED HERE*)

However, as stated on WordPress' own site, only one wpdb connection can exist at a time.

The $wpdb object can talk to any number of tables, but only to one database at a time; by default the WordPress database. In the rare case you need to connect to another database, you will need to instantiate your own object from the wpdb class with your own database connection information.

My question to you guys is: How do I create a new wpdb object after the first? It doesn't work to unset() the first database.

My workflow is: Query one DB, get data and store in variable, query next DB, get data and store in variable ... etc.

Edit: My question isn't a duplicate, since I'm looking for a way to create more than one new wpdb object.

I need to create a new wpdb object, access the external DB through it and store result in variable, then create ANOTHER new wpdb object and do the same and so on.

However, it only works for the first new wpdb object. It has to be because of the quote from WordPress' site. If I comment out the first wpdb object then the second one works.

  • Sorry but what error are you getting by creating the wpdb object? It seems fine to me. – Laxmana Apr 26 '17 at 14:04
  • 1
    Possible duplicate of Using wpdb to connect to a separate database – cjbj Apr 26 '17 at 15:03
  • As an alternative, you could consider using the REST API to pull in the other data. – WebElaine Apr 26 '17 at 15:32
  • It's only when creating the SECOND new DB connection, that it doesn't work. – user3452005 Apr 26 '17 at 19:32
  • This is NOT a duplicate of that question. I know how to create a new wpdb object. However, create a second, third, fourth etc. wpdb object in the same code doesn't work – user3452005 Apr 26 '17 at 19:37
1

The $new_db_connection is your new db object.

Just use that to access the other db, ie.

$new_db_connection->get_row("your query");
  • That's what I'm doing. And it works. For the FIRST external DB. When I try to create another new DB connection, it doesn't work. – user3452005 Apr 26 '17 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.