You can use default Magento MysqlFactory
this way (outside the magento):
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
ini_set('memory_limit', '5G');
error_reporting(E_ALL);
use Magento\Framework\App\Bootstrap;
require 'app/bootstrap.php';
// Code
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
/** @var \Magento\Framework\DB\Adapter\Pdo\MysqlFactory $adapterFactoryMysql */
$adapterFactoryMysql = $objectManager->get('Magento\Framework\DB\Adapter\Pdo\MysqlFactory');
$config = [
'host' => 'localhost',
'dbname' => 'magendo_botapi',
'username' => 'userName',
'password' => 'userPassword',
'model' => 'mysql4',
'engine' => 'innodb',
'initStatements' => 'SET NAMES utf8;',
'active' => '1',
'profiler' =>
[
'class' => '\Magento\Framework\DB\Profiler',
'enabled' => true,
],
];
/** @var \Magento\Framework\DB\Adapter\Pdo\Mysql $customMysqlAdapter */
$customMysqlAdapter = $adapterFactoryMysql->create(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, $config);
$sql = 'SHOW TABLES';
try {
$result = $customMysqlAdapter->query($sql);
var_dump($result->fetchAll());
} catch (\Magento\Framework\Exception\LocalizedException $e) {
echo $e->getMessage();
die();
} catch (Zend_Db_Adapter_Exception $e) {
echo $e->getMessage();
die();
}
Just change your settings ($config
).
This way could be used in the magento using DI:
class CustomClass
{
/**
* @var \Magento\Framework\DB\Adapter\Pdo\MysqlFactory
*/
private $mysqlFactory;
/**
* @var \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
private $adapter;
/**
* @var []
*/
protected $config;
/**
* CustomClass constructor.
*
* @param \Magento\Framework\DB\Adapter\Pdo\MysqlFactory $mysqlFactory
*/
public function __construct(
\Magento\Framework\DB\Adapter\Pdo\MysqlFactory $mysqlFactory
) {
$this->mysqlFactory = $mysqlFactory;
$this->config = [
'host' => 'localhost',
'dbname' => 'magendo_botapi',
'username' => 'customUsername',
'password' => 'customPassword',
'model' => 'mysql4',
'engine' => 'innodb',
'initStatements' => 'SET NAMES utf8;',
'active' => '1',
'profiler' =>
[
'class' => '\Magento\Framework\DB\Profiler',
'enabled' => true,
],
];
}
/**
* @return \Magento\Framework\DB\Adapter\Pdo\Mysql
*/
private function getConnection(): \Magento\Framework\DB\Adapter\Pdo\Mysql
{
if (!$this->adapter) {
/** @var \Magento\Framework\DB\Adapter\Pdo\Mysql $customMysqlAdapter */
$this->adapter = $this->mysqlFactory->create(\Magento\Framework\DB\Adapter\Pdo\Mysql::class, $this->config);
}
return $this->adapter;
}
/**
* @return array|string
* @throws Zend_Db_Statement_Exception
*/
public function someTestFunction()
{
$adapter = $this->getConnection();
$sql = 'SHOW TABLES';
try {
$result = $adapter->query($sql);
return $result->fetchAll();
} catch (\Magento\Framework\Exception\LocalizedException $e) {
return $e->getMessage();
} catch (Zend_Db_Adapter_Exception $e) {
return $e->getMessage();
}
}
}