The advice @SharkyKZ gave in the February 2024 topic SQL connect to external database -- Illegal offset type was spot on. The following code extracted from a working module shows how the class DatabaseFactory is resolved.It gives me the error:
"Class "Mycompany\Component\Test\Site\Model\Joomla\Database\DatabaseFactory" not found
The example retrieves the connection details of the external database from the configuration parameters of the module. The $db object has all the methods to access the database schema from localhost. No PHP native functions like mysql_options are required.
Code:
<?phpuse Joomla\CMS\Factory;use Joomla\Database\DatabaseFactory;use RuntimeException;...$external= array(); $external['driver'] = 'mysqli'; $external['host'] = 'localhost';$external['database'] = $params->get('database', '');$external['prefix'] = $params->get('dbprefix', '') . '_';$external['user'] = $params->get('dbuser', '');$external['password'] = $params->get('dbpassword', '');...// external database connection$database = new DatabaseFactory();try {$db = $database->getDriver('mysqli', $external);} catch (\RuntimeException $exception) {Factory::getApplication()->enqueueMessage(Text::sprintf('JLIB_DATABASE_ERROR_FUNCTION_FAILED', $e->getCode(), $e->getMessage()),'warning');}if (empty($db)) {throw new RuntimeException("Joomla did not return a database object.");}$query = $db->getQuery(true)->select('guest, client_id')->from('#__session');$db->setQuery($query);try{$sessions = (array) $db->loadObjectList();} catch (RuntimeException $e) {$sessions = [];}
Statistics: Posted by toivo — Wed Aug 28, 2024 3:02 am