Using wpdb to connect to a different database is not working

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.