2

I am trying to connect a second database to my wordpress site so that I may ask for data from it and display it in a table on my site. I have tried multiple ways of doing so. I have tried to use php to connect in the wp-config.php file and I have tried ways of connecting via the function.php file.

This is the code I attempted in the config file:

$mydb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
var_dump($mydb);

This is what I attempted in the function file: (I tried these separately, not both at the same time.)

function seconddb() {
    global $seconddb;
    $seconddb = new wpdb(USERNAME, PASSWORD, DATABASE_NAME, HOSTNAME);
}
add_action('init', 'seconddb');

Every time I attempt this, it breaks my site. I am adding the correct info/credentials of course. I am unsure if I am adding code in the wrong locations in the files, or if there should be other corresponding code elsewhere but I cannot get this to work for me.

I have not been able to find a tutorial that holds my hand enough for this. I could really use some guidance that doesn't include telling me to find someone to do it for me. I would like to do this myself. Thanks!

0

I have found that the following works for connecting the database via the theme's functions.php file. I placed this code snippet at the end of the existing code in the file. Even though the fatal error threw several line errors when trying to access the site, it only came down to wpdb having an extra d in it. This code now properly connects the secondary database with no errors. When using this, please remember to replace the information in parenthesis with the correct information applicable to the secondary database that you are trying to connect to the site.

    function seconddb() {
             global $seconddb;
             $seconddb = new 
             wpdb('Username','password','database name','localhost');
    }
    add_action('init','seconddb');

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.