This is how I am attempting to connect to the database on heroku:
//db.php
$config = array(
'username' => 'username',
'password' => 'password',
'connection_string'=> sprintf('mongodb://%s:%d','EXAMPLE.herokuapp.com','27017')
);
$connection = new \MongoClient($config['connection_string']);
When I pushed to the repo, and go to the app URL the follow error message is shown:
Failed to connect to: EXAMPLE.herokuapp.com:27017 Connection refused in db.php.
How should I format the connection_string so that it will not give the error message?
There is no locally running MongoDB available on Heroku.
You need to use one of the add-ons at https://addons.heroku.com/#data-stores such as MongoLab.
When you run
$ heroku addons:add mongolab
it's provisioned for you, and there will be a config variable in the environment with the connection information:
$ heroku config | grep MONGOLAB_URI
MONGOLAB_URI => mongodb://heroku_app1234:random_password#ds029017.mongolab.com:29017/heroku_app1234
You can just read that from $_ENV['MONGOLAB_URI'], or using getenv('MONGOLAB_URI'):
$connection = new \MongoClient(getenv('MONGOLAB_URI'));
Related
I am trying to use a PHP connection to connect MySQL Database which is on phpmyadmin. Nothing fancy about the connection just trying to see whether the connection is successful or not. I am using MAMP to host the database, the connection I am trying to use is this:
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;dbname=AppDatabase", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
I have been using postman to test to see if the connection is working, but I keep receiving this error message:
Connection failed: SQLSTATE[HY000] [2002] Connection refused
Before I was receiving an error message of:
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
This was because I had set the servername to localhost, through changing this to the IP address it has given me connection refused and I have no idea what is wrong.
Any help regarding this would be appreciated.
I found the reason why the connection was not working, it was because the connection was trying to connect to port 8888, when it needed to connect to port 8889.
$conn = new PDO("mysql:host=$servername;port=8889;dbname=AppDatabase", $username, $password);
This fixed the problem, although changing the server name to localhost still gives the error.
Connection failed: SQLSTATE[HY000] [2002] No such file or directory
But it connects successfully when the IP address is entered for the server name.
In my case MySQL sever was not running. I restarted the MySQL server and issue was resolved.
//on ubuntu server
sudo /etc/init.d/mysql start
To avoid MySQL stop problem, you can use the "initctl" utility in Ubuntu 14.04 LTS Linux to make sure the service restarts in case of a failure or reboot. Please consider talking a snapshot of root volume (with mysql stopped) before performing this operations for data retention purpose[8]. You can use the following commands to manage the mysql service with "initctl" utility with stop and start operations.
$ sudo initctl stop mysql
$ sudo initctl start mysql
To verify the working, you can check the status of the service and get
the process id (pid), simulate a failure by killing the "mysql"
process and verify its status as running with new process id after
sometime (typically within 1 minute) using the following commands.
$ sudo initctl status mysql # get pid
$ sudo kill -9 <pid> # kill mysql process
$ sudo initctl status mysql # verify status as running after sometime
Note : In latest Ubuntu version now initctl is replaced by systemctl
I spent quite a few hours in a docker environment where all my containers are docker containers and I was using Phinx for migrations. Just to share different responses with different configurations.
Working solutions
"host" => "db", // {docker container's name} Worked
"host" => "172.22.112.1", // {some docker IP through ipconfig - may change on every instance - usually something like 172.x.x.x} Worked
Non-working solutions
"host" => "127.0.0.1", // SQLSTATE[HY000] [2002] Connection refused
"host" => "docker.host.internal", // SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name does not resolve
"host" => "localhost", // SQLSTATE[HY000] [2002] No such file or directory
I was running Phinx in following way.
docker compose --env-file .env run --rm phinx status -e development
Using MAMP I changed the host=localhost to host=127.0.0.1. But a new issue came "connection refused"
Solved this by putting 'port' => '8889', in 'Datasources' => [
Using MAMP ON Mac, I solve my problem by renaming
/Applications/MAMP/tmp/mysql/mysql.sock.lock
to
/Applications/MAMP/tmp/mysql/mysql.sock
1. server cert verify flag
I was required to use SSL to connect, and needed to set PDO::MYSQL_ATTR_SSL_VERIFY_SERVER_CERT to false in the new PDO options array, besides the entry PDO::MYSQL_ATTR_SSL_CA for the CA file.
Without it, the mysql log on the server helpfully mentions
2021-07-27 17:02:51 597605 [Warning] Aborted connection 597605 to db: 'unconnected' user: 'unauthenticated' host: '192.168.10.123' (This connection closed normally without authentication)
where I was definitely passing the right db and username and such in the DSN. An empty options array will show the db and user in the error log, at least. I am sure there is a valid, technical reason for these things.
I am adding this information so I can more easily find it, the next time I end up on this page..
2. host in connection string
In the context of SSL, I've also seen the error when using the IP address instead of the hostname to connect, if the hostname was used as CN (Common Name) in the certificate.
For me was php version from mac instead of MAMP, PATH variable on .bash_profile was wrong. I just prepend the MAMP PHP bin folder to the $PATH env variable. For me was:
/Applications/mampstack-7.1.21-0/php/bin
In terminal run vim ~/.bash_profile to open ~/.bash_profile
Type i to be able to edit the file, add the bin directory as PATH variable on the top to the file:
export PATH="/Applications/mampstack-7.1.21-0/php/bin/:$PATH"
Hit ESC, Type :wq, and hit Enter
In Terminal run source ~/.bash_profile
In Terminal type which php, output should be the path to MAMP PHP install.
I had the same issue on a docker container from php:8.0-fpm-alpine image. I just added the following line in the Dockerfile and it fixed the issue:
RUN apk add mysql-client
I had a similar problem once, turned out the User in the database was created with something like:
CREATE USER 'webpage'#'localhost' IDENTIFIED BY 'password';
worked fine when the connection details php script had localhost, but not when the IP address was there. A quick swap (ip address when creating user and localhost in connection details) revealed those two things have to match.
For everyone if you still strugle with Refusing connection, here is my advice. Download XAMPP or other similar sw and just start MySQL. You dont have to run apache or other things just the MySQL.
I am using Predis PHP library to connect to redis server running on AWS EC2 server. When I try to connect to redis installed on my local system, it works fine. Same code does not work when I try to connect to Redis on AWS EC2. I receive below error.
php_network_getaddresses: getaddrinfo failed: No such host is known. [tcp://my-server-address:6379]
I tried to check connect server on redis-cli using below command and it works fine.
redis-cli -h my-server-address -p 6379
below is the code PHP that I use to connect to Redis.
function config() {
$client = new Predis\Client([
'scheme' => 'tcp',
'host' => 'my-server-address',
'port' => 6379,
'database' => 1,
]);
return $client;
}
I made sure that there is nothing wrong with my server address.
I am using mongoDB with PHP. on local system it works fine. Now I am trying to access mongoDB cluster on AWS which is secured by SSH. I am using below code
$conn = new MongoClient('mongodb://SSH Hostname', [
'username' => 'username',
'password' => '',
'db' => 'DBname'
]);
print_r($conn);
It gives below error
Type: MongoConnectionException
Message: Failed to connect to: SSH Hostname :27017: Connection refused
I can connect DB from MongoDB compass or Studio 3T. How I can use SSH while connecting using PHP
I am developing an laravel app using ubuntu as OS and my database is in a remote Azure Server.
After long a research I'm about to give up. Installed freetds, php5-sybase etc etc.
here is my connection file: (the default is set to sqlsrv)
....
'sqlsrv' => array(
'driver' => 'sqlsrv',
'host' => 'myhostname:myport',
'database' => 'mydatabasename',
'username' => 'myusername',
'password' => 'mypassword'
),
....
and the error that I am getting is this one:
PDOException
SQLSTATE[01002] Adaptive Server connection failed (severity 9)
Any sugestions? If you guys need more details please ask :)
Thanks in advance
I solved my problem. It was missing #domain in my query string example:
$pdo = new PDO("dblib:host=xxxx:1433;dbname=yyyy", 'username#domain', 'password');
I get solution in Read from the server failed when trying to connect to sql-azure from tsql
Edit /etc/freetds/freetds.conf file and use 8.0 TDS version.
If haven't this file install FreeTDS with
sudo apt-get install freetds-bin
Check these:
port separator is "," on windows and ":" on linux/Mac. Since you have 1433, the default one, it is better probably not to use it at all
definitely test first from command line using one of these :
$ tsql -S sectionNameInFreetdsconf -U user -P pass
$ tsql -H hostname -p port -U user -P pass
locate freetds.conf on your disk. It is possible it exists in several places and tsql uses one while PHP used another one. Best is to symlink them into one common file and test on that. Note that a common place for that file is ~/.freetds.conf beside /etc/ or /usr/local/etc/
there should be a [global] section on your freetds.conf file. Put there these lines :
tds version = 8.0
text size = 20971520
client charset = UTF-8
When i try connect to mysql with clear PHP, its working fine.
My code
$link = mysql_connect('hostname', 'username', 'password');
if (!$link) {
die('Could not connect');
}
if(mysql_select_db('dbname')){
echo 'Connected successfully';
}
But when im trying to connect with yii, then getting the error
My config/main.php
'db'=>array(
'class'=>'CDbConnection',
'connectionString' => 'mysql:host=hostname;dbname=dbname',
'emulatePrepare' => true, /* I try false too*/
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
),
This is output for exception what i print in open() function framework/db/CDbConnection.php
Exception handle here
protected function open()
{
if($this->_pdo===null)
{
if(empty($this->connectionString))
throw new CDbException('CDbConnection.connectionString cannot be empty.');
try
{
Yii::trace('Opening DB connection','system.db.CDbConnection');
$this->_pdo=$this->createPdoInstance();
$this->initConnection($this->_pdo);
$this->_active=true;
}
catch(PDOException $e)
{
echo '<pre>';
var_dump($e); die;
if(YII_DEBUG)
{
throw new CDbException('CDbConnection failed to open the DB connection: '.
$e->getMessage(),(int)$e->getCode(),$e->errorInfo);
}
else
{
Yii::log($e->getMessage(),CLogger::LEVEL_ERROR,'exception.CDbException');
throw new CDbException('CDbConnection failed to open the DB connection.',(int)$e->getCode(),$e->errorInfo);
}
}
}
}
Exception text
"SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client"
I see in display
CDbException
CDbConnection failed to open the DB connection.
My PHP VERSION 5.5.36 Mysql version 5.5.35
My Hosting is i-page dot com
Yii Version '1.1.13'
Thanks for help.
It appears to be a problem with the way the passwords are hashed and the version of MySQL and the MYSQL_PDO library.
Yii uses PDO to query the database, thats why clear PHP works like a charm and Yii doesn't.
To verify this, try this:
$mysqlConnection = new PDO("mysql:host=hostname;dbname= dbname", "username", "password");
this line should throw the following error:
PDO::__construct(): The server requested authentication method unknown to the client [mysql_old_password].
This error is the equivalent to the MySQL 2045:
"SQLSTATE[HY000] [2054] The server requested authentication method unknown to the client
If you confirm that the problem is related to PDO you have several options but you need to access the hosting system (or ask them to fix the problem):
Sign in to MySQL and execute the following command SET PASSWORD FOR 'username'#'hostname' = OLD_PASSWORD('password'); (this will fix the hashing of the pasword)
Upgrade the MYSQL PDO Library (PDO_MYSQL) to match the version of MYSQL on the server.
I got this problem with Yii 1.1.x project and almost got crazy:
First make sure you have
sudo apt install php-xml php-mbstring php-pdo php-mysql
installed, and restart apache
sudo apachectl restart
or:
sudo service apache2 restart
Detailed error was that database library cannot be found.
My solution was related to caching:
cache' => array(
'class' => 'system.caching.CDbCache',
//'class' => 'system.caching.CFileCache',
'connectionID'=>'db', // <<< THIS IS THE ISSUE
),
if connectionID is not set, db caching defaults to mysqli database in /protected/data directory which cannot be accessed if mysqli driver is not installed on system (common issue with dedicated servers, DO droplets, xampp/wamp...)
or, you can disable db caching and enable fileCache instead.