• Resolved fixedbug

    (@fixedbug)


    Hi,

    I have a problem connecting to database from another site of mine with wpdb class. I have found a number of different examples, but it still doesn’t work no matter what I do.

    So I basically want to create an object of wpdb class in the site that needs some data from another site that has those data stored in database, in table postmeta.

    Here is the code in functions.php:

    
    function secondDB() {
    global $mydb;
    $mydb = new wpdb('username', 'pass', 'dbname', 'host');
    $result = $mydb->get_var( "SELECT meta_value FROM $mydb->postmeta WHERE meta_key = 'my-meta-key' AND post_id = 96");
    echo $result;
    }
    add_action( 'init', 'secondDB' );
    

    However, $result has no value that could be printed. Even if I try a query as simple as SELECT COUNT(*) FROM $mydb->users, I get no result.

    I am sure that all of the database connection details are correct. I copied them from the wp-config file from the site on which this database is.

    Am I making some mistake? And if not, where could be the error?

    Please note that when I execute the same query on the site where this database actually is, it returns a value. Also, sometimes while trying to get it to work, I get an error: “object of class wpdb could not be converted to string”.

    Thank you in advance.

Viewing 1 replies (of 1 total)
  • Have you tried to echo your SQL statement because when I did it $mydb->postmeta returns nothing so you will have a malformed sql statement.

    You don’t need the global statement because you’re not bringing $newdb in from elsewhere.

    Note that I’m using Kint to export the values. Much nicer than echo / print_r.

        $newdb = new wpdb('wp881', 'wp881', 'wp881-3', 'localhost');
        !d($newdb->postmeta);
        $sql = "SELECT meta_value FROM $newdb->postmeta WHERE meta_key = '_locations' AND post_id = 131";
        !d($sql);
        $result = $newdb->get_var($sql);
        !d($result);

    Returns:

    • $newdb->postmeta null
    • $sql string (71) “SELECT meta_value FROM WHERE meta_key = ‘_locations’ AND post_id = 131”
    • $result null
    • This reply was modified 6 years, 10 months ago by zagreus.
    • This reply was modified 6 years, 10 months ago by zagreus.
Viewing 1 replies (of 1 total)
  • The topic ‘WPDB – Connecting to external database using wpdb does not work’ is closed to new replies.