MongoDB PHP Driver "No suitable servers found" - php

I'm installing a MongoDB on Debian 9 but when I try to connect
"No suitable servers found (serverSelectionTryOnce set): [connection refused calling ismaster on '127.0.0.1:27017']" is raised.
The machine runs
Debian 9
PHP PHP 7.0.27-0+deb9u1
MongoDB Version 3.6.5
MongoDB database driver 1.6.16 (stable) MongoDB driver for PHP 1.4.3 (stable)
I googled all the pages that talked about this thread but nothing.
I also changed the mongod.conf, deleted the ipv6 lookback, but nothing.
The script that I launch in PHP is
use MongoDB\Client;
$user = 'xxxx';
$pwd = 'yyyy';
$host = '127.0.0.1';
$port = '27017';
$db_name = 'my_db';
$mongo = new Client("mongodb://".$user.":".$pwd."#".$host.":".$port);
return $mongo->selectDatabase($db_name);
When I try to
selectDatabase()
the exception was raised
PS: Of course, $user and $pwd are credentials of a user that I correctly create in "admin" Mongo's table
{
"_id" : "admin.root",
"user" : "root",
"db" : "admin",
"credentials" : {
"SCRAM-SHA-1" : {
"iterationCount" : 10000,
"salt" : "<hidden>",
"storedKey" : "<hidden>",
"serverKey" : "<hidden>"
}
},
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Help please o_O
EDIT: Before deploying the project on live server I tested it on MAMP and everything work properly (in particular the connection with Mongo DB)

Related

Slim Framework and connection to AS400

I tried to connect to AS400 using Php Slim Framework.
It returned to me an error about odbc connection php function.
I edited this framework files this way.
SETTINGS.PHP
<?php
declare(strict_types=1);
use App\Application\Settings\Settings;
use App\Application\Settings\SettingsInterface;
use DI\ContainerBuilder;
use Monolog\Logger;
return function (ContainerBuilder $containerBuilder) {
// Global Settings Object
$containerBuilder->addDefinitions([
SettingsInterface::class => function () {
return new Settings([
'displayErrorDetails' => true, // Should be set to false in production
'logError' => false,
'logErrorDetails' => false,
'logger' => [
'name' => 'slim-app',
'path' => isset($_ENV['docker']) ? 'php://stdout' : __DIR__ . '/../logs/app.log',
'level' => Logger::DEBUG,
],
"db" => [
'name' => 'EDDXXXXXXX',
'username' => 'XXXXXXX',
'password' => 'XXXXXXXX',
'connection' => 'xxxxxx.xxx.xxxxx'
]
]);
}
]);
};
DEPENDENCIES.PHP
<?php
declare(strict_types=1);
use App\Application\Settings\SettingsInterface;
use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$loggerSettings = ...........CODE HERE ..........
return $logger;
},
PDO::class => function (ContainerInterface $c) {
$settings = $c->get(SettingsInterface::class);
$dbSettings = $settings->get('db');
$name = $dbSettings['name'];
$username = $dbSettings['username'];
$password = $dbSettings['password'];
$dsn = "Driver={Client Access ODBC Driver (32-bit)};System=" .
$connection . ";libraries=" . $name .
";naming=system;transaction isolation=read committed;Uid=" .
$username .";Pwd=" . $password . ";";
//return new PDO($dsn, $username, $password);
return odbc_connect($dsn, $username, $password);
},
]);
};
ROUTES.PHP
$app->get('/db-test', function (Request $request, Response $response) {
$db = $this->get(PDO::class);
$sth = $db->prepare("SELECT * FROM XXXX");
$sth->execute();
$data = $sth->fetchAll(PDO::FETCH_ASSOC);
$payload = json_encode($data);
$response->getBody()->write($payload);
return $response->withHeader('Content-Type', 'application/json');
});
When i call /db-test I obtain this server error
"statusCode": 500,
"error": {
"type": "SERVER_ERROR",
"description": "ERROR: odbc_connect(): SQL error: [Microsoft][Driver Manager ODBC] Nome origine dati non trovato e driver predefinito non specificato., SQL state IM002 in SQLConnect on line 46 in file C:\\slim\\as400\\app\\dependencies.php."
}
I don't understand why it gives to me that error.
The odbc_connect function in your DI container is not correct, because it returns a resource, but not a PDO object. It should be return new PDO($dsn, $username, $password);
Data source name not found and default driver not specified., SQL state IM002. Make sure that the ODBC driver is installed and that the data-source name exists. I recommend to try this connection string for AS400.
Provider=IBMDA400;Data Source=MY_SYSTEM_NAME;User Id=myUsername; Password=myPassword;Default Collection=MY_LIBRARY;
or
Driver={IBM i Access ODBC Driver};System=mySystem;Uid=myUser;Pwd=myPassword;
File DSN for iSeries AS400 ODBC connection
https://www.connectionstrings.com/as-400/
My experience with PHP and IBM i is that you need to use the ODBC drivers, not PDO_ODBC. This experience is admittedly old, and may no longer be true, however, I looked at the current PHP 8.1 documentation for PDO_ODBC and found this:
ibm-db2
Supports access to IBM DB2 Universal Database, Cloudscape, and Apache Derby servers through the free DB2 express-C client.
unixODBC
Supports access to database servers through the unixODBC driver manager and the database's own ODBC drivers.
generic
Offers a compile option for ODBC driver managers that are not explicitly supported by PDO_ODBC.
On Windows, php_pdo_odbc.dll has to be enabled as extension in php.ini. It is linked against the Windows ODBC Driver Manager so that PHP can connect to any database cataloged as a System DSN.
So PDO_ODBC supports DB2 UDB. This is only one of the three flavors of DB2, and unfortunately not the one used by IBM i. So maybe you can get the generic ODBC PDO to work, but I would stick to just ODBC, not PDO unless you execute the spend money command and purchase the DB2 Connect product which will let you access the enterprise DB2 products (DB2 for i and DB2 for zOS) from a Windows/Unix/Linux box.

Yii 1: Could not find driver error when connecting to microsoft sql server

I successfully tested that my PHP can connect to my MS SQL SERVER.
<?php
$server = 'SRV-MEXAL';
// Connect to MSSQL
$link = mssql_connect($server, 'mexal_db_usr', 'password_changed');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
} else {
echo "Works <br>";
$OK = mssql_select_db ("at6_rp");
echo $OK ? "ok" : "ko";
}
?>
Using this script I got both Works and ok, so connection and db selection are both working.
I tried to configure my db connection into Yii 1 main.php
"mexal_db" => array (
'class' => "CDbConnection",
'connectionString' => 'sqlsrv:Server=SRV-MEXAL; Database=at6_rp',
'enableParamLogging' => false,
'username' => 'mexal_db_usr',
'password' => 'password_changed',
'charset' => 'utf8',
),
But when trying to instantiate it, I got this exception
CDbException' with message 'CDbConnection failed to open the DB connection: could not find driver' in /var/www/httpdocs/test1.phonix.it/yii/framework/db/CDbConnection.php:399
What am I doing wrong?
You will have php.ini inside your project folder. (In yii2, i am having inside web folder. In yii1, I don't know where php.ini file is located.)
So, please find your php.ini file of your project folder.
Inside php.ini, search for pdo_mssql.so.
;extension=pdo.so
;extension=pdo_mssql.so
Remove ; from it. Like
;extension=pdo.so
extension=pdo_mssql.so
Restart your server. It will work.
For more info, check this could not find driver - Yii

Connecting phalcon webapp to an AWS RDS mysql database

I am trying to connect my RDS to my phalcon app. I have settings in my security group that allows access to the database from my server and from localhost. Here is some of my code from my index.php file
$config = new Phalcon\Config\Adapter\Ini("../config/config.ini");
$di->set('db', function() use ($config){
try {
$db = new \Phalcon\Db\Adapter\Pdo\Mysql(array(
"host" => $config->development->host,
"username" => $config->development->username,
"password" => $config->development->password,
"dbname" => $config->development->dbname
));
} catch (Exception $e) {
die("<b>Error when initializing database connection:</b> " . $e->getMessage());
}
return $db;
});
Then I try a call to my database in one of my controllers here:
public function indexAction()
{
$users = Users::find();
echo "There are ", count($users), "\n";
}
When I run that controller the page times out and throws this error:
Error when initializing database connection: SQLSTATE[HY000] [2002] Operation timed out
The data in the config file is correct. I am able to connect to it just fine via the terminal. What am I doing wrong? Any thoughts/suggestions/insights? Thanks

Trouble with configuring users and connecting to Mongo with PHP

I installed mongo 3.0.0 on my ubuntu server.
I tried to use PHP (with appropriate lib installed) to connect to mongo to learn sth new. Unfortunaltey I cannot go any further.
My user configuration looks like this:
> use testdb
switched to db testdb
> show users
{
"_id" : "testdb.testdb",
"user" : "testdb",
"db" : "testdb",
"roles" : [
{
"role" : "readWrite",
"db" : "testdb"
}
]
}
Then I try to execute the following PHP code:
try{
$uri = "mongodb://testdb:password#xxx.xxx.xxx.xxx:27017/testdb";
$options = array("connectTimeoutMS" => 30000);
$client = new MongoClient($uri, $options );
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
die();
}
$db = $client->selectDB("testdb");
I get "Message: Failed to connect to: xxx.xxx.xxx.xxx:27017: Authentication failed on database 'testdb' with username 'testdb': auth failed".
In /etc/mongod.conf I have "auth = true" uncommented
I also verified the conncetion with:
> nc -w 3 -v xxx.xxx.xxx.xxx 27017 Connection to xxx.xxx.xxx.xxx 27017
> port [tcp/*] succeeded!
I dig through Internet, i spent few hours already on this, I even re-installed mongo and set everything up again without any success.
Could you point to where to look for solution?
The authentication schema of 3.0 is not compatible with 2.x drivers. One way you should be able to make it work is by downgrading the authentication mechanism:
use "admin"
var schema = db.system.version.findOne({"_id" : "authSchema"})
schema.currentVersion = 3
db.system.version.save(schema)
Then create a user and you should be able to connect with it.

how to connect to the database in openshift application

I did as following
MySQL 5.1 database added. Please make note of these credentials:
Root User: xxxxxxx
Root Password: xxxxxxx
Database Name: php
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
You can manage your new MySQL database by also embedding phpmyadmin-3.4.
The phpmyadmin username and password will be the same as the MySQL credentials above.
phpMyAdmin 3.4 added. Please make note of these MySQL credentials again:
Root User: xxxxxxx
Root Password: xxxxxxx
URL: https://php-doers.rhcloud.com/phpmyadmin/
and i try to connect db using bellow PDO code .but it does not work
$dbh = new PDO('mysql:host=mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/;dbname=php', "xxxxxx, "xxxxxx");
I don't know what is the connection URL mean ?
There is an error in your connection string plus $OPENSHIFT_MYSQL_DB_* are env variables and need to be fetched via getenv php function.
So try the following:
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
define('DB_PORT',getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER',getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
define('DB_PASS',getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
define('DB_NAME',getenv('OPENSHIFT_GEAR_NAME'));
$dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST.';port='.DB_PORT;
$dbh = new PDO($dsn, DB_USER, DB_PASS);
Open php myadmin from webconsole , and on left corner you will get some Ip
That is like xx.xx.xx.xx:3306 , so your hostname is xx.xx.xx.xx
Ip address wil work , I have tried and worked for me
below code worked for me ,try this it might help you
var mysql = require('mysql');
var mysql = require('mysql');
exports.pool = mysql.createPool({
host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost',
port: process.env.OPENSHIFT_MYSQL_DB_PORT || '3306',
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root',
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || '',
database: 'chichat' || 'chichat',
multipleStatements : true,
charset: 'utf8'
});
I would like to add some information to future reference.
Today I am trying to deploy a Drupal installation to Open Shift (OS) and tried to configure MySql.
I connected to OS via SSH (rhc ssh ), went to app-root/data/sites/default. Following cat settings.php to see how OS configure database.
Here it is:
// When run from Drush, only $_ENV is available. Might be a bug
if (array_key_exists('OPENSHIFT_APP_NAME', $_SERVER)) {
$src = $_SERVER;
} else {
$src = $_ENV;
}
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => $src['OPENSHIFT_APP_NAME'],
'username' => $src['OPENSHIFT_MYSQL_DB_USERNAME'],
'password' => $src['OPENSHIFT_MYSQL_DB_PASSWORD'],
'host' => $src['OPENSHIFT_MYSQL_DB_HOST'],
'port' => $src['OPENSHIFT_MYSQL_DB_PORT'],
'driver' => 'mysql',
'prefix' => '',
),
),
);
$conf['file_private_path'] = $src['OPENSHIFT_DATA_DIR'] . 'private/';
$conf['file_temporary_path'] = $src['OPENSHIFT_TMP_DIR'] . 'drupal/';
So I created a php folder into git repository (see OS documentation about Drupal), copied a clean Drupal install to it and paste code above to settings.php.
After pushing to git, restarted OS app and worked!

Categories