Using wpdb to connect to a separate database

  • I want to connect wpdb to another database. How do I create the instance and pass it the database name/username/password?


    Another MySQL database, or another database type? Do you still want access to the regular WordPress database, or are you moving the site from one DB to another?

    Yes, another MySQL database. It's a separate DB on the same server, and it's not a Wordpress one. It's a custom db, with information I want to display inside wordpress.

    If you did that with the $wpdb object, if it were even possible, it would disconnect the rest of WordPress from its existing database. So, not recommended. Another option is to create a new instance using EZSQL, which is used by WordPress. I think EZSQL is used because it's a layer that abstracts you from having to use php-pdo-mysql, php-mysql, or php-mysqli, not knowing which might be installed on a given server.

    Yes it's possible. wpdb can be instantiated to access any database and query any table.

  • Wadih M.

    Wadih M. Correct answer

    10 years ago

    Yes it's possible.

    The wpdb object can be used to access any database and query any table. Absolutely no need to be Wordpress related, which is very interesting.

    The benefit is the ability to use all the wpdb classes and functions like get_results, etc so that there's no need to re-invent the wheel.

    Here's how:

    $mydb = new wpdb('username','password','database','localhost');
    $rows = $mydb->get_results("select Name from my_table");
    echo "<ul>";
    foreach ($rows as $obj) :
       echo "<li>".$obj->Name."</li>";
    echo "</ul>";

    Booyah. Too bad all those comments added up on the question itself to block your accurate answer.

    @Jeremy Clarke: I agree. Hoping our fellow wordpressers will be more careful to not innocently spread out disinformation.

    you can also save time by using `global $wpdb`. But before firing $wpdb->get_results method, you must include wp-load.php as: `require_once('/your/wordpress/wp-load.php');`

    Set WPDB prefix to make WP_Query and get_post to generate correct sql query by calling `$mydb->set_prefix('wp_');`

    I know this is an old thread, but I can't help but feel squashing the `$mydb` variable with a new object could leave a connection open (I could be wrong). I would check to see if `$mydb` is already instantiated from a previous call, and if so, close the connection before spinning up a new instance. eg (sorry can't do neat Markdown code blocks in the comments): `if ($mydb != null) { $mydb->close(); }`

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM