Support » Fixing WordPress » Connecting with external database (functions.php?)

  • Klaas Koopman


    Hi everyone,

    I’ve been working on this for a week now and still can’t find the right answer.

    My situation:
    I’ve got another database (on same hosting as current site, so localhost), which I want to use data of in my theme files.

    $mydatabase = new mysqli("localhost","my_user","my_password","my_db");
    // Check connection
    if ($mydatabase -> connect_errno) {
      echo "Failed to connect to MySQL: " . $mydatabase -> connect_error;
    // Perform query
    if ($result = $mydatabase -> query("SELECT * FROM tableabc WHERE xandy='4'")) { (etc)

    Above is what is in my single_cpt.php file and that works. But I’ve heard I should not have this part in there: $mydatabase = new mysqli("localhost","my_user","my_password","my_db"); and I should use that part in Functions.php. Now i’ve tried to remove the above line and add the line below to functions.php, but can’t seem to get it to work.

    function connect_another_db() {
        global $my_db;
        $my_db= new wpdb('my_user','my_password','my_db', 'localhost');
    add_action('init', 'connect_another_db');

    Can someone please help me out, would really appreciate it!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Dion


    If you are familiar with using the mysqli functions (OOP or procedural), then by all means use them! Using $wpdb to connect with a second database introduces significant overhead and should IMO be avoided if at all possible.

    If the WordPress DB user has the access you require to the second database, then you can adjust your queries and use the already-existing handle created by the $wpdb class. The following code will obtain the handle:

    global $wpdb;
    $dbh = $wpdb->__get('dbh');

    However, keep in mind that you must use mysqli_*() procedural commands since that is how the handle was created.

    Klaas Koopman


    Dear Dion,

    Thank you for your reply.

    So you are saying I can have this part in my themefiles (singlecpt.php for example)

    $mydatabase = new mysqli("localhost","my_user","my_password","my_db");

    As i’ve been told that’s not a good idea and I should include it somehow into my functions.php?



    Since the PHP mysqli extension is available in all versions of PHP supported by WordPress, you can safely ignore those who told you to use new instance of $wpdb. (I would bet that those same people do not know how to use mysqli functions/methods and only know how to use $wpdb methods. šŸ™‚ )

    Just make sure to close the DB connection when you’re done with it. PHP will not immediately do so when a script ends, and it is a common cause of “too many connections” errors.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.