0

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

Amirition
  • 328
  • 5
  • 22

1 Answers1

0

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.

  • No, the MySQL is on another server and I can't use localhost and I literally mentioned that the credentials are correct and it's working fine on my localhost, Navicat and TEHplayground. – Amirition Aug 18 '21 at 12:20
  • Exactly, that's why you have to look at why it isn't working on this particular host. Some of the parameters differ, apparently. Please update your question with the real code, except for your credentials of course. Are they passed in as $variables? or literally put in the arguments? We cannot see that, but there must be something in your connection string that is off. – Robbert van den Bogerd Aug 18 '21 at 12:25
  • 1
    By the way, are you behind a firewall? Could it be that your server is blocking outgoing traffic to other servers, specifically port 3306 to other servers? – Robbert van den Bogerd Aug 18 '21 at 12:29
  • Yeah it might be that. I sent a ticket to the hosting support. – Amirition Aug 18 '21 at 12:48