XF 2.1 Cannot connect to external Mysqli database

rhodes

Active member
Hello,

I would like to access a non XF2 mysqli database from a custom addon.

PHP:
<?php
namespace mynamespace;

class myClass
{
.....
    public static function myfunction($mediaKey, array $site, $siteId) {
     ...
        $mysqli = new \mysqli($this_host,$this_user,$this_pw,$this_db);
....

Unfortunately, the attempt to connect to Mysqli causes an error: Could not fetch Mysqli.

The database exists. I use the same call successfully in another PHP script, but without namespace.

Any idea what I could do?

Regards, rhodes
 
Not entirely sure. I've seen comments about the database connection being closed too early and trying to execute statements afterwards.

BUT...

Regardless of what the solution ends up being, please don't bypass XF's database handling for this. It doesn't matter if it's a non-XF database, you should still use the XF database adapter to connect to it. There's no reason to avoid it and lots of reasons why you should use it.

All you need to do is:

PHP:
$db = new \XF\Db\Mysqli\Adapter([
    'host' => $this_host,
    'username' => $this_user,
    'password' => $this_pw,
    'dbname' => $this_db
]);

This will likely work without issue, assuming there's no issue with the database server itself, it provides you with many handy functions to execute and format query results, and most importantly is safer because it makes it trivial to use prepared statements.
 
PHP:
$mysqli = new \XF\Db\Mysqli\Adapter([
    'host' => $this_host,
    'username' => $this_user,
    'password' => $this_pw,
    'dbname' => $this_db
  ]);
$mysqli->getConnection();
I have now tried this out. It works perfectly on my local development environment. Unfortunately, it does not work on the live system. The log files there say "connection refused". I have checked the access data several times.
Any idea what the reason could be?
 
Connection refused seems like there’s something blocking the connection. Maybe your server isn’t allowed through the remote firewall to make the connection.
 
Top Bottom