Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Connect multiple database in WordPress?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 2.23k
    Comment on it

    Hello readers, today I guide you "To Connect Multiple Database in WordPress".

    In WordPress, wpdb is the class which handles all the database related tasks. In arrears WordPress installation we have $wpdb object of that class using which we will be doing database related tasks like INSERT, UPDATE, DELETE etc. But here the restriction is the fact that we can do these tasks within the database in which WordPress is installed.

    Means using $wpdb you cannot do any database query through which WordPress is not installed.

     

    But now-a-times it is quite frequent requirement from clients that your WordPress code needs to discuss with multiple database and when we get this sort requirement for the first time we generally think's "ahh how it can be done". Although after doing some Google you're able to know that this is not a major deal as WordPress wrote wpdb class in such a nice way that you can create any number of objects for different database connection. Therefore the idea is WordPress created the $wpdb object to discuss with the database in which WordPress installed in the same way, you can create another object of the same class to do the SQL functions in several databases.

     

    Below is the example to create a new database connection. Put this code into your wp-config.php file.

     

    <?php
      $newdb = new wpdb( 'USERNAME' , 'PASSWORD' , 'DATABASE NAME' , 'HOST' );
    ?>

     

    Use the above object this object you can do whatever you want to do with this new database like below.

     

    <?php
      $results = $newdb->get_results( "SELECT <SOME FIELDS> FROM <TABLE NAME> WHERE <SOME CONDITION>" );
     foreach ( $results as $result ) {
       echo $result->fieldname;
     }
    ?>

     

    That's it. I hope it helps you.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: