0

I am attempting to use wordpress built in database functionality to connect to a different database on local host. I am doing this in functions.php.

I have no problem achieving this with mysqli, the connection is made and I can test this by printing out the table names inside this database or any other query. However this is not the case with wpdb.

This is working :

$db = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

This is not working:

$db = new wpdb(DB_USER, DB_PASSWORD, DB_DATABASE, DB_SERVER);

$mytables=$db->get_results("SHOW TABLES");
foreach ($mytables as $mytable)
{
    foreach ($mytable as $t) 
    {       
        echo $t . "<br>";
    }
}

It does not show anything regardless of what query I use, I just get a blank page with a 200 response, indicating nothing is wrong but no data was found. Where as mysqli will show me the data without any problems.

I would just use mysqli but I want to use prepared statements, which does not seem to be an option on wordpress. I need to get that wpdb connectiong working if anyone could give me some clues as to why this does not work.

1
  • Where do you call it? Do you hook in the init action? Does this part where you echo your result return any output?
    – moped
    Feb 3, 2020 at 7:17

1 Answer 1

0

I found the problem.

I had defined variables using the names DB_USER, DB_PASSWORD etc in my own database connection config file. I then found that wordpress already defines variables using these exact same names, which are stored in one of the files in the wp-includes directory. So my own defined variables with the same name were being overwritten or ignored when I attempted to use a wpdb connection.

The reason my own defined variables worked for my_sqli and not wpdb is, I assume, that calling a wpdb connection would fire up the script with these defined connection variables inside. I discovered this when using var_dump on the wpdb connection, where I discovered a completely random username was used instead of my own.

So if you want to use a wpdb connection and connect to a database with differing connection details, do not define variables named DB_USER, DB_PASSWORD, DB_SERVER and DB_DATABASE. Choose different names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.