I am having problems with a connection to the database, specifically, when I try to access the system and the database does not respond.
I am getting an error in my services.php file.
And this is the code:
try{
$di->set('db', function () use ($config) {
$config = $config->get('database')->toArray();
$dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
if (stripos($config['adapter'], 'Mysql')!== false) {
$mi_conf = array(
"host" => $config['host'],
"username" => $config['username'],
"password" => $config['password'],
"dbname" => $config['dbname'],
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
)
);
} else {
$mi_conf = array(
"dbname" => '//'.$config['host'].'/'.$config['dbname'],
"username" => $config['username'],
"password" => $config['password'],
'charset' => 'utf8'
);
}
unset($config['adapter']);
return new $dbClass($mi_conf);
});
} catch (Exception $e) {
$error .= 'db, ';
return null;
}
I do not know if it will be necessary to change there or I have to make changes to each call from each model.
Any advice?
Thank you.
The code looks without errors.
Use setShared to avoid connecting to the database multiple times, or use the "persistent" attribute on the configuration to take effect. Maybe it does the trick. By the way, change the try catch to the moment where the service was created, so you can catch the exception.
$di->setShared('db', function () use ($config) {
try {
$config = $config->get('database')->toArray();
$dbClass = 'Phalcon\Db\Adapter\Pdo\\' . $config['adapter'];
if (stripos($config['adapter'], 'Mysql') !== false) {
$mi_conf = array(
"host" => $config['host'],
"username" => $config['username'],
"password" => $config['password'],
"dbname" => $config['dbname'],
"persistent" => false,
"options" => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
),
);
} else {
$mi_conf = array(
"dbname" => '//' . $config['host'] . '/' . $config['dbname'],
"username" => $config['username'],
"password" => $config['password'],
"persistent" => false,
'charset' => 'utf8',
);
}
unset($config['adapter']);
return new $dbClass($mi_conf);
} catch (Exception $e) {
$error .= 'db, ';
return null;
}
});
Related
I cannot connect to SAP using PHP sapnwrfc, this is my code :
use SAPNWRFC\Connection as SapConnection;
use SAPNWRFC\Exception as SapException;
$config = [
'GROUP' => '*****', // Group/Server
'MSHOST' => '*****', // Message Server
'CLIENT' => '*****', // System ID
'SYSNR' => '*****', // Instance Number
'USER' => '*****', // Username
'PASSWD' => '*****', // Password
'SAPROUTER' => '*****', // SAP Router
'TRACE' => SapConnection::TRACE_LEVEL_OFF, // Trace
];
try {
$c = new SapConnection($config);
$f = $c->getFunction('*****');
$result = $f->invoke();
echo "<pre>";
print_r($result);
echo "<pre>";
} catch(SapException $ex) {
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
}
Is there something wrong? Please help me.
Thankyou in advance.
I am writing a database class which is going to connect to my pdo database. This class is using this config file to get the information needed:
<?php
return [
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'database_name' => 'books',
'database_type' => 'mysql',
'options' => []
];
And this is the database class:
<?php
class DB
{
public static function connect($config)
{
try {
return new PDO([
$config['database_type'] . ':host=' . $config['host'] . ';dbname=' . $config['database_name'],
$config['username'],
$config['password'],
$config['options']
]);
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I am getting this error:
Fatal error: Uncaught TypeError: PDO::__construct() expects parameter
1 to be string, array given in and etc...
I am wondering what I did wrong, sicne I don't see any syntax mistakes in my code.
You have an extra set of brackets:
return new PDO([
...
]);
... shouldn't have the [ and ] respectively; they're turning your four function parameters into a single array parameter. You want simply
return new PDO(
...
);
HTH!
I've set up a new PHP predis connection to a redis server using the documented code. I can verify it's connected ok, but I don't know how to simply test if the connection exists.
$options = array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => $port,
'instance' => 'myinstance',
'timeout' => '0.100' // possibly add this to connections?
);
$sentinels = [
"tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];
$connection = new Predis\Client($sentinels, [
'replication' => 'sentinel',
'service' => $options['instance'],
]);
if ($connection->isConnected() === true) {
// undocumented-- I don't think this works?
echo "connected";
} else {
echo "failed"; // this is what gets echoed
}
Is there a method to test if the connection is good short of actually reading / writing to it? isConnected() doesn't appear to work.
As suggested by #drot:
$options = array(
'scheme' => 'tcp',
'host' => '127.0.0.1',
'port' => $port,
'instance' => 'myinstance',
'timeout' => '0.100' // possibly add this to connections?
);
$sentinels = [
"tcp://{$options['host']}:{$options['port']}?timeout={$options['timeout']}",
];
$connection = new Predis\Client($sentinels, [
'replication' => 'sentinel',
'service' => $options['instance'],
]);
// do this:
$connection->connect();
if ($connection->isConnected() === true) {
// undocumented-- I don't think this works?
echo "connected";
} else {
echo "failed"; // this is what gets echoed
}
$servername1 = "localhost1";
$username1 = "user1";
$password1 = "pwd";
$dbname1 = "dbs1";
$servername2 = "localhost2";
$username2 = "user2";
$password2 = "ped2";
$dbname2 = "dbs2";
// Create connection
$conn = new mysqli($servername1, $username1, $password1, $dbname1);
// Check connection
if ($conn->connect_error) {
$conn = new mysqli($servername2, $username2, $password2, $dbname2);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
}
Can this type of connection be implemented?? when i implement this deliberately making an error in first database credentials i get a warning that Unknown MySQL server host 'localhost1'
and doesn't load the page. why is this not working?
I make a list of databases and then iterate through them and try to connect. It should be no problem using multiple databases. Using localhost1 and localhost2 (only localhost is possible which is 127.0.0.1) is not possible. You should use IP addresses.
Here is the code:
<?php
$Databases = array(
0 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database1',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_3,
),
1 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database2',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_2,
),
2 => array(
'db_kind' => 'postgres',
'host' => $server1[$server1["current"]]["host"],
'port' => $server1[$server1["current"]]["port"],
'db_name' => 'database3',
'username' => 'xxx',
'password' => 'yyy',
"type"=>DB_TYPE_1,
),
);
for($i=0;$i<count($Databases);$i++)
{
if($last_db_ind>=count($Databases)){
$last_db_ind=0;
}
if(($db =& db_connect($last_db_ind++))==false){
echo 'Connection failed for DB: '. $Databases["db_name"] . ', DB index: '.$last_db_ind;
continue;
}
?>
You should either use "localhost" or an IP address to connect to the SQL server. In your case it tries to connect to "localhost1" (as in you variable) which doesn't exists (unless you changed your host file). Try using IPs (127.0.0.1 for localhost and any other for the backup)
Cheers,
JCK
You Can try Ping first.
OR
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ")
" . $mysqli->connect_error;
}
OR
extension_loaded("mysql");
I have the following scenario:
class ModelManager extends EntityManager implements ModelManagerInterface
{
public function __construct($conn, $options = array())
{
$isDev = empty($options['is_dev']) ? false : $options['is_dev'];
// #see Doctrine\ORM\EntityManager#create()
$config = ArrayUtils::arrayMergeRecursiveRight($options, array(
'cache' => $isDev ? new Cache\ArrayCache : new Cache\ApcCache,
'queryCache' => $isDev ? new Cache\ArrayCache : new Cache\ApcCache,
'modelsProxiesPath' => getcwd() . '/cache/ModelProxies',
));
// create Configuration object
if (is_array($options)) {
$config = $this->initConfig($options);
if (!$config->getMetadataDriverImpl()) {
throw ORMException::missingMappingDriverImpl();
}
}
// test EventManager object
$eventManager = empty($options['eventManager']) ? new EventManager() : $options['eventManager'];
switch (true) {
case ($conn instanceof \PDO):
$conn = array(
'driver' => 'pdo_' . $conn->getAttribute(\PDO::ATTR_DRIVER_NAME),
'pdo' => $conn,
);
print_r($conn);
$conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager);
break;
case (is_string($conn)):
$pdo = new \PDO($conn);
if ('oci8' !== $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME)) {
$conn = array(
'driver' => 'pdo_' . $pdo->getAttribute(\PDO::ATTR_DRIVER_NAME),
'pdo' => $pdo,
);
} else {
$conn = $this->mapDsnToDoctrine($conn);
}
$conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager);
break;
case (is_array($conn)):
$conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager);
break;
case ($conn instanceof Connection):
if ($eventManager !== null && $conn->getEventManager() !== null) {
throw ORMException::mismatchedEventManager();
}
break;
default:
throw new Exception\InvalidArgument("Invalid argument: " . json_encode($conn));
}
// parent constructor
// #see Doctrine\ORM\EntityManager#__construct()
parent::__construct($conn, $config, $conn->getEventManager());
}
// ...
}
This is used smth like this:
self::$em = new ModelManager(
new \PDO(self::$config['db_adapter']['connection']['dsn']),
empty(self::$config['db_adapter']['options']['doctrine']) ?
array() : self::$config['db_adapter']['options']['doctrine']
);
$tool = new \Doctrine\ORM\Tools\SchemaTool(self::$em);
$classes = $this->db(self::$config['db_adapter']['options']['doctrine']['modelsPath']);
$tool->updateSchema($classes);
Where the config looks like this:
$config = array(
'db_adapter' => array(
'connection' => array(
'dsn' => 'mysql://root:******#localhost/netistest' . time(),
),
'options' => array(
'doctrine' => array(
'cache' => 'ArrayCache|ApcCache', // development|testing&production
'queryCache' => 'ArrayCache|ApcCache', // development|testing&production
'modelsPath' => __DIR__ . '/NetisTest/Model',
'modelsProxiesPath' => __DIR__ . '/cache/doctrine/ModelProxies',
'modelsProxiesNamespace' => 'App\Models\Proxies',
'modelsProxiesAutogenerate' => 'App\Models\Proxies',
),
'zend' => array(
// at this moment we decided not to implement Zend\DbAdapter
),
)
),
);
The problem with all this strange configuration, is that, after instantiating the ModelManager class, when trying to interrogate the database for creating the tables associated to my models, it throws the following error:
Doctrine\DBAL\DBALException: An exception occurred while executing 'SHOW FULL TABLES WHERE Table_type = 'BASE TABLE'':
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php:91
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:699
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/Connection.php:630
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php:206
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php:250
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/dbal/lib/Doctrine/DBAL/Schema/AbstractSchemaManager.php:986
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/SchemaTool.php:855
/home/dragosc/workspace/athem-repositories/Component_NetisDb/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/SchemaTool.php:832
/home/dragosc/workspace/athem-repositories/Component_NetisDb/tests/NetisTest/Db/Setup/Doctrine.php:51
You can find the code (however in an older form) here as well:
https://github.com/athemcms/Component_NetisDb/blob/master/library/Netis/Db/ModelManager/ModelManager.php
Can anyone please help me in understanding why PDO isn't enough for EntityManager to remember the database as well ?
Thanks a lot in advance!