Constructor failed on creating a new PDO connection

257 Views Asked by At

I'm trying to access a remote MySQL server. I created a user in the remote server and granted all the remote privileges to all hosts. This is my code for connecting to database:

<?php
try{
    $dsn = "mysql:host=MY_REMOTE_SERVER_IP;dbname=DB_NAME;port=3306";
    $db = new PDO($dsn, 'USER_NAME','PASSWORD');
}catch(Exception $e){
    echo $e->getMessage();
}

The code is working fine on my localhost. I even tried the code on some Playgrounds and it's working fine. But on my website, it's not working. The website does not connect to the database and always returns Constructor failed error.

The PHP version is 7.4 on my website and it supports PDO. But I don't know why it does not make the connection?

This is a picture of the error: Error Message

1

There are 1 best solutions below

4
Robbert van den Bogerd On

Just guessing: you maybe should not use the remote ip address, but localhost or 127.0.0.1 for your database host.

According to the pdo source code, this error message means the connection failed, which is not really helpful, but could mean one of these things (but not limited to):

  • hostname is wrong
  • database name is wrong
  • credentials are wrong
  • some networking issue
  • you name it :)

My prime suspect is the hostname, but just make sure all parameters are correct.